ASP.NET MVC 3 @Html.DropDownListFor 忽略 selectedValue
在我的 asp.net MVC 3 项目中,我想创建一个与公司相关的联系人。
您可以直接创建联系人或通过公司详细信息视图并添加新联系人并传递companyId,以设置联系人创建表单下拉列表中已有的公司。
问题是我无法在下拉列表中将通过的公司作为默认值。
Global.asax
routes.MapRoute("contactCreate", "contact/toevoegen/{companyid}", new { action = "ContactCreate", controller = "Backend", companyid = UrlParameter.Optional });
控制器方法
public ActionResult ContactCreate(int? companyid)
{
Contact contact = new Contact();
ViewBag.StatusList = srep.getContactStatusses();
ViewBag.CompanyId = companyid;
return View(contact);
}
View
@model xxx.Models.Contact
...
<div class="editor-label">
@Html.LabelFor(model => model.bedrijf_id)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.bedrijf_id, new SelectList(ViewBag.Bedrijven, "bedrijf_id", "bedrijf_naam",ViewBag.CompanyId), "--Kies bedrijf--")
@ViewBag.CompanyId
@Html.ValidationMessageFor(model => model.bedrijf_id)
</div>
...
@ViewBag.CompanyId 有一个值。
知道为什么它没有设置选定的值吗?
In my asp.net MVC 3 project I would like to create a contact that's related to a company.
You can either directly create a contact OR go via the company details view and add a new contact passing the companyId to set that company already in the dropdown on the contact create form.
The problem is that I can 't get the passed company as default in my dropdown.
Global.asax
routes.MapRoute("contactCreate", "contact/toevoegen/{companyid}", new { action = "ContactCreate", controller = "Backend", companyid = UrlParameter.Optional });
Controller method
public ActionResult ContactCreate(int? companyid)
{
Contact contact = new Contact();
ViewBag.StatusList = srep.getContactStatusses();
ViewBag.CompanyId = companyid;
return View(contact);
}
View
@model xxx.Models.Contact
...
<div class="editor-label">
@Html.LabelFor(model => model.bedrijf_id)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.bedrijf_id, new SelectList(ViewBag.Bedrijven, "bedrijf_id", "bedrijf_naam",ViewBag.CompanyId), "--Kies bedrijf--")
@ViewBag.CompanyId
@Html.ValidationMessageFor(model => model.bedrijf_id)
</div>
...
@ViewBag.CompanyId has a value.
Any idea why it's not setting the selected value?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当执行“DropDownListFor”时,它将尝试将从模型传入的值与所选值进行匹配。因此,在您的示例中,它将使用“bedrijf_id”作为所选值。看起来您希望所选值来自模型之外的值。
从评论中我认为你想要的只是一个 DropDownList ,如下所示:
希望这会有所帮助。
When doing a "DropDownListFor" it will try to match up the value passed in from the model for the selected value. So in your example it will use "bedrijf_id" as the selected value. It looks like you want the selected value to be from something outside of your model.
From the comments I think what you want is just a DropDownList as follows:
Hope this helps.