Learning MVC - Maintaining model state

Posted by GenericTypeTea on Stack Overflow See other posts from Stack Overflow or by GenericTypeTea
Published on 2010-06-12T10:52:13Z Indexed on 2010/06/12 11:03 UTC
Read the original article Hit count: 333

Filed under:
|
|

First of all, I'm very new to MVC. Bought the books, but not got the T-Shirt yet.

I've put together my first little application, but I'm looking at the way I'm maintaining my model and I don't think it looks right.

My form contains the following:

<% using (Html.BeginForm("Reconfigured", null, FormMethod.Post, new { id = "configurationForm" })) { %>  

   <%= Html.DropDownList("selectedCompany", 
       new SelectList(Model.Companies, Model.SelectedCompany), 
       new { onchange = "$('#configurationForm').submit()" })%>

   <%= Html.DropDownList("selectedDepartment", 
       new SelectList(Model.Departments, Model.SelectedDepartment), 
       new { onchange = "$('#configurationForm').submit()" })%>

   <%=Html.TextArea("comment", Model.Comment) %>
<%} %>  

My controller has the following:

public ActionResult Index(string company, string department, string comment)
{

    TestModel form = new TestModel();
    form.Departments = _someRepository.GetList();
    form.Companies = _someRepository.GetList();

    form.Comment = comment;
    form.SelectedCompany = company;
    form.SelectedDepartment = department;

    return View(form);

}

[HttpPost]
public ActionResult Reconfigured(string selectedCompany, 
   string selectedDepartment, string comment)
{
    return RedirectToAction("Index", new { company = selectedCompany, 
       department = selectedDepartment, comment = comment}); 
}

And finally, this is my route:

routes.MapRoute(
    "Default", 
    "{controller}/{company}/{department}",
    new { controller = "CompanyController", action = "Index", company="", 
       department="" }
);

Now, every time I change DropDownList value, all my values are maintained. I end up with a URL like the following after the Reconfigure action is called:

http://localhost/Main/Index/Company/Sales?comment=Foo%20Bar

Ideally I'd like the URL to remain as:

http://localhost/Main/Index

My routing object is probably wrong.

This can't be the right way? It seems totally wrong to me as for each extra field I add, I have to add the property into the Index() method?

I had a look at this answer where the form is passed through TempData. This is obviously an improvement, but it's not strongly typed? Is there a way to do something similar but have it strongly typed?

This may be a simple-enough question, but the curse of 10 years of WinForms/WebForms makes this MVC malarky hard to get your head 'round.

© Stack Overflow or respective owner

Related posts about mvc

Related posts about asp.net-mvc-2