Views Tipped in ASP.NET MVC, using ViewBag

0

I wonder if every View in Mvc has to be typed?

I want to get values from a form but these values are not from the same entity. I'm using a helper:

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

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

    
asked by anonymous 11.10.2014 / 20:28

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 database.

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

[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);
}
    
11.10.2014 / 22:44