English 中文(简体)
mvc 4 模式无效
原标题:mvc 4 Model is null

i m using razor s listboxfor for the first time, but my Model is always null. after reading similar posts and tryouts it still won t work.

个人.cshtml

@model SampleApp.Web.ViewModel.个人意见

@{
     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>

个人主计长c

[AcceptVerbs(HttpVerbs.Get)]
    [ValidateAntiForgeryToken]
    public ActionResult GetListBoxData()
    {
        var data = new List<个人意见>();
        data.Add(new 个人意见{Name = "Test", Surrname="testsurrname", Age=30});

        var viewModel = new 个人意见()
        {
            ListboxData = data.AsEnumerable().Select(s=> new SelectListItem{Value=s.Name ,Text = s.Surrname}),
        };

        return View(viewModel);
    }

    [AcceptVerbs(HttpVerbs.Post)]
    [ValidateAntiForgeryToken]
    public ActionResult GetListBoxData(个人意见 persondata)
    {
        //TODO: handle values from View
        return View(this);
    }

    [ValidateAntiForgeryToken]
    [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Create([Bind(Include = "Name, Surrname, Age")]  个人意见 persondata)
    {
        try
        {
            PersonService personDataProvider = new PersonService();
            personDataProvider.SavePerson(persondata);

            return new RedirectResult("SomewhereToGo");
        }
        catch (DataException ex)
        {
            //TODO: Log
        }

        return View(this);
    }

个人意见

public class 个人意见
{
    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; }
}

writing values from editFor to db works as expected without code for listboxfor. after adding it to my html it should be filled from db on page loading, but I get a ReferenceNotSet Exception on page loading. Model.ListboxData is null, before GetListBoxData action is called.

感谢你们的帮助!

问题回答
  1. Your form should submit the data via POST, not GET. And, you don t need to use enctype = "multipart/form-data", unless you want to upload files through your from.
  2. You need two Index Actions in your Controller, one is for sending the data from your Controller to the View, and the other one is for getting the data back from the View, when the form is submitted (POST) to the server.
  3. The first argument you pass to your ListBox (the expression) refers to the Property in your Model that the selected item from your ListBox will be stored in, which in this case is 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
}

顺便说一句,在你看来,你不必像现在这样界定你的名字。

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




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签