【发布时间】:2013-08-27 18:23:38
【问题描述】:
我是第一次使用 razor 的 listboxfor,但我的 Model 始终为空。 在阅读了类似的帖子和试用后,它仍然无法正常工作。
Person.cshtml
@model SampleApp.Web.ViewModel.PersonViewModel
@{
ViewBag.Title = "Welcome";
}
<article>
<p>
Welcome to example page.
</p>
<p>
<div class="container">
//Post data works as expected, controllers create method write to db successfully
@using (Html.BeginForm("Create", "Person", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Personen</legend>
<div class="editor-label">
@* @Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Surrname)
</div>
</fielset>
</div>
<p>
<input type="submit" value="Create" />
</p>
}
//binding to Model fails, Model is null. Not be able to debug anything in controller action, it stops when "loading" the page
@using (Html.BeginForm("GetListBoxData", "Person"))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
@Html.ListBoxFor(model => model.ListboxData, Model.ListboxData);
}
</div>
PersonController.cs
[AcceptVerbs(HttpVerbs.Get)]
[ValidateAntiForgeryToken]
public ActionResult GetListBoxData()
{
var data = new List<PersonViewModel>();
data.Add(new PersonViewModel{Name = "Test", Surrname="testsurrname", Age=30});
var viewModel = new PersonViewModel()
{
ListboxData = data.AsEnumerable().Select(s=> new SelectListItem{Value=s.Name ,Text = s.Surrname}),
};
return View(viewModel);
}
[AcceptVerbs(HttpVerbs.Post)]
[ValidateAntiForgeryToken]
public ActionResult GetListBoxData(PersonViewModel persondata)
{
//TODO: handle values from View
return View(this);
}
[ValidateAntiForgeryToken]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Include = "Name, Surrname, Age")] PersonViewModel persondata)
{
try
{
PersonService personDataProvider = new PersonService();
personDataProvider.SavePerson(persondata);
return new RedirectResult("SomewhereToGo");
}
catch (DataException ex)
{
//TODO: Log
}
return View(this);
}
PersonViewModel
public class PersonViewModel
{
public int PersonId{ get; set; }
public int Age { get; set; }
public string Name { get; set; }
public string Surrname { get; set; }
public IEnumerable<SelectListItem> ListboxData { get; set; }
}
将值从 editFor 写入 db 按预期工作,无需 listboxfor 代码。 将它添加到我的 html 后,它应该在页面加载时从 db 填充,但在页面加载时我得到一个 ReferenceNotSet 异常。在调用 GetListBoxData 操作之前,Model.ListboxData 为 null。
非常感谢您的帮助!
【问题讨论】:
-
为什么你的视图文件中模型声明后有一个“
”?
-
不好意思,之前有一些html代码,从cshtml复制粘贴
-
Person.cshtml?您的控制器是 Index.... 您有 Person 操作吗?因为默认情况下它会通过它。通常你会有 index.cshtml
标签: c# asp.net-mvc asp.net-mvc-4 razor html.listboxfor