MVC Updatemodel 未从 DropDownList 更新
我的编辑屏幕上有以下内容:
<label for="campaign.CandidateID">Candidate:</label>
<%= Html.DropDownList("Campaign.CandidateID", Model.Candidates, "Choose...")%>
<%= Html.ValidationMessage("CandidateID", "*") %>
在我的控制器中:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues)
{
Campaign campaign = repos.GetCampaign(id);
try
{
UpdateModel(campaign);
repos.Save();
return RedirectToAction("Index", "Admin");
}
catch
{
return View(new CampaignDTO(campaign));
}
当我编辑记录并更改文本字段时,一切正常,但是当我更改连接到下拉列表的项目时,更改不会在活动对象中更新。我已经检查了 this.ValueProvider["Campaign.CandidateID"]
并且数据就在那里!
顺便说一句,在显示编辑屏幕期间,它正在选择列表中选择正确的候选者。
问题可能是因为 ValueProvider 提供的是字符串,而我的类中的 CandidateID 是 int 吗?
我很困惑。
I have the following on my edit screen:
<label for="campaign.CandidateID">Candidate:</label>
<%= Html.DropDownList("Campaign.CandidateID", Model.Candidates, "Choose...")%>
<%= Html.ValidationMessage("CandidateID", "*") %>
and in my controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id, FormCollection formValues)
{
Campaign campaign = repos.GetCampaign(id);
try
{
UpdateModel(campaign);
repos.Save();
return RedirectToAction("Index", "Admin");
}
catch
{
return View(new CampaignDTO(campaign));
}
When I edit the record and change text fields, everything works perfectly, but when I change an item connected to a dropdownlist, the change does not get updated in the campaign object. I have checked this.ValueProvider["Campaign.CandidateID"]
and the data is in there!
By the way, during the display of the edit screen, it is selecting the correct Candidate in the select list.
Could the problem come from the fact that ValueProvider is providing a string whereas CandidateID in my class is an int?
I'm stumped.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否也在文本字段的名称前添加“Campaign”前缀(即 Html.TextBox("Campaign.Name")?当您调用 UpdateModel 而不指定前缀时,ValueProvider 字典中包含前缀的任何数据(即“Campaign.Name”)? CandidateID”)将不符合绑定到模型对象的资格。这就是为什么您会在 ValueProvider 字典中看到“Campaign.CandidateID”条目(因为它已成功发布在请求中),但它没有绑定到您的营销活动对象。
Are you prefixing the text field's name with "Campaign" as well (i.e. Html.TextBox("Campaign.Name")? When you call UpdateModel without specifying a prefix, any data in the ValueProvider dictionary that contains a prefix (i.e. "Campaign.CandidateID") won't be eligible for binding to the model object. Which is why you see the "Campaign.CandidateID" entry in the ValueProvider dictionary (because it was successfully posted in the request), but it isn't being bound to your Campaign object.