c# - mvc 4 模型为空

标签 c# asp.net-mvc asp.net-mvc-4 razor html.listboxfor

我是第一次使用 razor 的 listboxfor,但我的模型始终为空。 在阅读了类似的帖子和试用后,它仍然无法正常工作。

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);
    }

人物 View 模型

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 后,它应该在页面加载时从数据库中填充,但我在页面加载时收到 ReferenceNotSet 异常。在调用 GetListBoxData 操作之前,Model.ListboxData 为空。

非常感谢您的帮助!

最佳答案

  1. 您的表单应通过 POST 而不是 GET 提交数据。而且,你不需要使用 enctype = "multipart/form-data",除非你想通过你的 from 上传文件。
  2. 在 Controller 中需要两个索引操作,一个用于将数据从 Controller 发送到 View ,另一个用于在将表单提交 (POST) 到服务器时从 View 取回数据.
  3. 您传递给 ListBox 的第一个参数(表达式)指的是模型中的属性,您的 ListBox 中的所选项目将存储在该属性中,在本例中为 PersonId。

因此,您的 View 应如下所示:

@model MVCApplication.Web.ViewModel.PersonViewModel 

@using (Html.BeginForm("Index", "Person"))
{
    @Html.ListBoxFor(model => model.PersonId, Model.ListBoxData)

    <input type="submit" value="Save" />
} 

然后,在您的 Controller 中,您将有两个这样的操作:

public ActionResult Index()
{
    var viewModel = new PersonViewModel()
    {
        ListboxData = data.Select(s => new SelectListItem { Value = s.PersonId.ToString(), Text = s.PersonId.ToString() }).AsEnumerable();
    };

    return View(viewModel);
}

[HttpPost]
public ActionResult Index(PersonViewModel viewModel)
{
  // code to save the data in the database or whatever you want to do with the data coming from the View
}

顺便说一句,在您的 ViewModel 中,您不必像那样定义 ListBoxData 属性,只需这样做:

public class PersonViewModel
{
    public int PersonId{ get; set; }
    public IEnumerable<SelectListItem> ListBoxData { get; set; }
}

关于c# - mvc 4 模型为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18424198/

相关文章:

jquery-mobile - 如何仅在 ASP.NET MVC 4 Razor 移动网站中将单个 View 锁定为纵向

c# - Web Api 不会使用 jQuery Ajax 和 Basic Auth 下载文件

c# - 使用反射进行深度扫描 - 有更好的方法吗?

c# - 有没有办法在程序中伪造 DirectShow 过滤器?

c# - 如何从 nuget 包中获取项目/解决方案的名称

css - Bootstrap 脚本和样式不起作用

c# - 当变量更改时收到通知

asp.net-mvc - ASP .NET MVC5 中的 CORS

asp.net - jQuery UI 对话框 + 验证

javascript - jquery密码验证