开发者

ViewModel approach interferes with ModelBinding in MVC 2 when using the new "For" HTML helpers

I am using .net MVC 2.0 and have set up an edit view that receives a custom ViewModel object. The ViewModel is a class with two properties:

// Properties
public Portfolio Portfolio { get; private set; }
public SelectList slSectors { get; private set; }

In my view there is a form with the purpose of updating the Portfolio Object. The SelectList is passed so I can have a dropdown list for the sectors related to a portfolio. Nothing special here, and exactly as I did it in 1.0.

The problem arises when I use the new TextBoxFor and DropDownListFor helper methods.

I am setting them up like this:

<%= Html.ValidationMessageFor(model => model.Portfolio.SectorID)%>
<%= Html.LabelFor(model => model.Portfolio.SectorID)%>
<%= Html.DropDownListFor(model => model.Portfolio.SectorID, Model.slSectors, new { @class = "selectInput" })%>

<%= Html.ValidationMessageFor(model => model.Portfolio.Title)%>
<%= Html.LabelFor(model => model.Portfolio.Title)%>
<%= Html.TextBoxFor(model => model.Portfolio.Title, new { @class = "textInput" })%>

These are producing the following HTML output (respectively):

<span class="field-validation-valid" id="form0_Portfolio_SectorID_validationMessage"></span> 
<label for="Portfolio_SectorID">SectorID</label> 
<select class="sele开发者_如何学GoctInput" id="Portfolio_SectorID" name="Portfolio.SectorID"><option selected="selected" value="2">Education</option> 

Law

<span class="field-validation-valid" id="form0_Portfolio_Title_validationMessage"></span> 
<label for="Portfolio_Title">Title</label> 
<input class="textInput" id="Portfolio_Title" name="Portfolio.Title" type="text" value="Portfolio Title" />

Please note that the name and id attributes now carry the "Portfolio" prefix. I assume this is because they are being derived from "model.Portfolio.X". This seems to be interfering with my ability to apply Model Binding in the Controller in the Edit ActionResult.

The ActionResult is as follows:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formData)
{
    var portfolio = Repository.GetPortfolio(id);

    if (portfolio == null)
        return RedirectToAction("NotFound");


    try
    {
        UpdateModel(portfolio);
        portfolio.DateUpdated = DateTime.Now;
        Repository.Save();
        return RedirectToAction("Index");
    }
    catch (Exception e)
    {
        ModelState.AddModelError("_Form", e.Message);
    }

    return View(new vmPortfolio(portfolio));

}

How can I either (a) stop the "Portfolio" prefix from being applied in the View, or (b) get ModelBinding working with it present.

Thanks,

Mike

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜