mvc 4 模型为空

问题描述 投票:0回答:1

我第一次使用剃刀的列表框,但我的模型始终为空。 阅读类似的帖子并尝试后,它仍然无法工作。

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

人视图模型

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 为 null。

非常感谢您的帮助!

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

所以,你的视图应该如下所示:

@model MVCApplication.Web.ViewModel.PersonViewModel 

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

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

然后,在你的控制器中,你将有两个像这样的操作:

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; }
}
© www.soinside.com 2019 - 2024. All rights reserved.