【发布时间】:2016-08-29 00:57:48
【问题描述】:
不确定我做错了什么,但我的下拉菜单不想选择我希望它选择的值。我有以下
控制器操作
// GET: /Contract/Create
public ActionResult Create()
{
var model = new ContractViewModel();
var authors = _authorService.GetAuthors();
var publishers = _publisherService.GetPublishers();
model.AuthorsList = new SelectList(authors, "AuthorID", "Name", authors.First());
model.PublishersList = new SelectList(publishers, "PublisherID", "Name", publishers.First());
return View(model);
}
// POST: /Contract/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ContractViewModel contractViewModel)
{
if (ModelState.IsValid)
{
Contract contract = new Contract();
contract.CanUsePublisherPartners = contractViewModel.CanUsePublisherPartners;
contract.Author.AuthorID = Convert.ToInt32(contractViewModel.SelectedAuthorID);
contract.Publisher.PublisherID = Convert.ToInt32(contractViewModel.SelectedPublisherID);
var success = _contractService.AddContract(contract);
if (success)
{
return RedirectToAction("Index");
}
}
contractViewModel.AuthorsList = new SelectList(_authorService.GetAuthors(), "AuthorID", "Name");
contractViewModel.PublishersList = new SelectList(_publisherService.GetPublishers(), "PublisherID", "Name");
ViewBag.ErrorMessage = "An error occured when trying to add the Contract. A contract between this Author and Publisher may already exist! Please try again and if the problem persists, contact the Sys Admin.";
return View(contractViewModel);
}
视图模型
public class ContractViewModel
{
[Display(Name = "Can the author distribute through the publisher's partners?")]
public bool CanUsePublisherPartners { get; set; }
[Display(Name="Author")]
public int? SelectedAuthorID { get; set; }
[Display(Name = "Publisher")]
public int? SelectedPublisherID { get; set; }
public SelectList AuthorsList { get; set; }
public SelectList PublishersList { get; set; }
}
查看下拉列表的绑定
<div class="form-group">
@Html.LabelFor(model => model.SelectedAuthorID, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.HiddenFor(m => m.SelectedAuthorID)
@Html.DropDownListFor(m => m.SelectedAuthorID, Model.AuthorsList)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.SelectedPublisherID, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.HiddenFor(m => m.SelectedPublisherID)
@Html.DropDownListFor(m => m.SelectedPublisherID, Model.PublishersList)
</div>
</div>
有什么问题? 当我提交表单时,SelectedAuthorID 和 SelectedPublisherID 的值默认为 int - 0。
我真的很无语,我查看了一些细节,试图找出它们是否会影响任何东西。例如。当 Selected 容器属性与列表项的 value 属性同名时,有些人会遇到麻烦。
如果有人有任何建议会很高兴分享他们!
【问题讨论】:
标签: c# .net asp.net-mvc dropdownlistfor