我正在使用.net MVC 2.0并设置了一个接收自定义ViewModel对象的编辑视图 . ViewModel是一个具有两个属性的类:
// Properties
public Portfolio Portfolio { get; private set; }
public SelectList slSectors { get; private set; }
在我看来,有一个表单旨在更新投资组合对象 . SelectList被传递,所以我可以有一个与投资组合相关的行业的下拉列表 . 这里没什么特别的,就像我在1.0中所做的一样 .
当我使用新的TextBoxFor和DropDownListFor帮助器方法时出现问题 .
我这样设置它们:
<%= 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" })%>
它们分别产生以下HTML输出:
<span class="field-validation-valid" id="form0_Portfolio_SectorID_validationMessage"></span>
<label for="Portfolio_SectorID">SectorID</label>
<select class="selectInput" id="Portfolio_SectorID" name="Portfolio.SectorID"><option selected="selected" value="2">Education</option>
法
<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" />
请注意,name和id属性现在带有“Portfolio”前缀 . 我认为这是因为它们来自“model.Portfolio.X” . 这似乎干扰了我在Edit ActionResult中在Controller中应用模型绑定的能力 .
ActionResult如下:
[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));
}
我怎样才能(a)停止在视图中应用“Portfolio”前缀,或者(b)让ModelBinding与它一起使用 .
谢谢,
麦克风