rebelliard rebelliard - 1 month ago 15
C# Question

Reuse model data in a post action

In my viewmodel, I have a list of items I fetch from the database and then send to the view. I would like to know if it's possible to avoid having to refill the options property whenever I hit a Post action and need to return the model (for validation errors and what not)?

In webforms, this wouldn't be necessary.

Edit: I was not clear. My problem is with the SelectList options I use for my DropDownLists. Everything gets posted, but if I have to return to the view (model is invalid), I have to reload the options from the database! I want to know if this can be avoided.

My viewmodel:

public class TestModel
{
public TestModel()
{
Departments = new List<SelectListItem>();
}

public string Name { get; set; }
public int Department { get; set; }
public IEnumerable<SelectListItem> Departments { get; set; }
}


My view:

@model MvcApplication1.Models.TestModel
@using (Html.BeginForm())
{
@Html.TextBoxFor(m => m.Name)

@Html.DropDownListFor(m => m.Department, Model.Departments)

<input type=submit value=Submit />
}


My controller (do notice the comment on HttpPost):

public ActionResult Index()
{
TestModel model = new TestModel
{
Name = "Rafael",
Department = 1,
Departments = new List<SelectListItem>
{
new SelectListItem { Text = "Sales", Value = "1" },
new SelectListItem { Text = "Marketing", Value = "2", Selected = true },
new SelectListItem { Text = "Development", Value = "3" }
}
};

// Departments gets filled from a database.

return View(model);
}

[HttpPost]
public ActionResult Index(TestModel model)
{
if (!ModelState.IsValid)
{
//Do I have to fill model.Departments again!?!?!?

return View(model);
}
else { ... }
}


Thanks in advance.

Edit: FYI, my solution was to use the
Session
variable.

Answer

Just need to strongly type your view, and change your controller method to have a parameter of that class type.

That is, the view

@model MyNamesspace.Models.MyModel
...
@using (Html.BeginForm())
{
    ....
}

And you controller method which is posted to.

[HttpPost]
public ActionResult MyAction(MyModel model)
{
    ...
}

EDIT: Also make sure you have form fields for each property of the model which you need posted to the controller. My example is using Razor too BTW.