I'm new to mvc and I'm struggling with this model stuff. My understanding is that I can only use one model per action.
public class TestModel
{
public string foo1 { get; set; }
public string foo2 { get; set; }
public string foo3 { get; set; }
}
I want to partially load my model in the normal action:
public ActionResult Index()
{
TestModel model = new TestModel();
model.foo1 = "foo1";
return View(model);
}
Then the user should add data to the model from the view.
@model SAS_MVC.Models.Test.TestModel
@using (Html.BeginForm())
{
@Html.EditorFor(model => model.foo1, new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model.foo2, new { htmlAttributes = new { @class = "form-control" } })
@Html.EditorFor(model => model.foo3, new { htmlAttributes = new { @class = "form-control" } })
<input type="submit" value="submit" />
}
According to the user's data I have to add further data in the post controller:
[HttpPost]
public ActionResult Index(MyModel model, FormCollection form)
{
// get some data from DB
model.foo3 = 123;
return View(model);
}
How can I save this model permanently? I have problems with e.g. foo3 is empty in the view. I want to pass the model between the post-controller and view several times without losing data.
I did try with TempData and ViewBag but for me this is very uncomfortable to work with... no intellisense.
So how can I do it right? Thanks for help!
Update with EF6:
public class MyEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
public class TestController : Controller
{
DB03SASModel dbModel = new DB03SASModel();
// GET: Test
public ActionResult Index()
{
MyEntity model = new MyEntity();
model.Name = "AAAA";
dbModel.MyEntities.Add(model);
dbModel.SaveChanges();
return View(model);
}
[HttpPost]
public ActionResult Index(MyEntity model)
{
model.Name = "BBBB";
dbModel.SaveChanges();
//UpdateModel(model);
return View(model);
}
}
View
@model SAS_MVC.MyEntity
@using (Html.BeginForm())
{
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.DisplayFor(model => model.Id, new { htmlAttributes = new { @class = "form-control" } })
@Html.HiddenFor(model => model.Id, new { htmlAttributes = new { @class = "form-control" } })
<input type="submit" value="submit" />
}
Now I save the model using EF Code First and I checked it in the DB --> every thing is well saved. But: Again the view take the wrong value and I still struggle. I found out the the @Html.HiddenFor provide me the current ID of the entity in the post controler. Than I changed the value to "BBBB" and than I pass the exact same entity back to the view but the view never did an update! I don't get it sorry. When I try with UpdateModel(model); "AAAA" is again my value! Where did this value come from? In the DB there is no such value at this time!! What did I wrong??