Views Typed in ASP.NET MVC, using Viewbag

Asked

Viewed 931 times

0

I wonder if all View on Mvc has to be typed?

I want to take values from a form but those values are not from the same entity. I am using a helper:

@Html.TexBoxFor(model => model.Nome)

I would like to know how to get the value of this helper without having to use model => model.Nome whereas nome is a property of an entity. When my view type does not take the value of textbox.

  • Where are these other values you need to take?

  • I want to do the following. Create a form that will insert information in more than one table in the event click save button. But when like View I can only use the properties of that entity that it was typed. I hope I was clear.

1 answer

1

In this case, you need to create a Viewmodel. A Viewmodel is identical to a Model, but does not store information in a bank.

Put into it all the properties of the various Models that will be saved. By sending to Controller, you will have to create the Models manually and enter the information ViewModel.

[HttpPost]
public ActionResult MinhaAction(MeuViewModel viewModel) 
{
    if (ModelState.IsValid) 
    {
        var model1 = new MeuModel1();
        model1.Prop1 = viewModel.Prop1;
        model1.Prop2 = viewModel.Prop2;
        ...
        context.MeuModel1.Add(model1);
        context.SaveChanges();

        var model2 = new MeuModel2();
        model2.Prop1 = viewModel.Prop3;
        model2.Prop2 = viewModel.Prop4;
        ...
        context.MeuModel2.Add(model2);
        context.SaveChanges();

        return RedirectToAction("OutraAction"); 
    }

    // Caso o ViewModel não seja válido, cai aqui.
    return View(viewModel);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.