开发者

Model binder woes

开发者 https://www.devze.com 2023-04-10 17:15 出处:网络
why do I always have so much trouble with the model binder??I have the following controller: namespace X.Web.Controllers

why do I always have so much trouble with the model binder?? I have the following controller:

namespace X.Web.Controllers
{
    public class ExpertsVM
    {
        public string GivenName;
        public string Surname;
    }

    public class AuthController : Controller
    {
        [HttpPost]
        public ActionResult RegisterExpert(ExpertsVM v)
        {

and my view looks like this:

@using X.Web.Controllers
@model ExpertsVM

@using (Html.BeginForm("RegisterExpert", "Auth"))
{
    @Html.EditorFor(x => x.GivenName)
    @Html.EditorFor(x => x.Surname)

so the form gets rendered like this:

<form action="/Auth/RegisterExpert" method="post">
<input class="text-box single-line" id="GivenName" name="GivenName" type="text" value="" />
<input class="text-box single-line" id="Surname" na开发者_如何学JAVAme="Surname" type="text" value="" />

but when the action gets invoked, v contains all nulls. if I declare the action like this:

[HttpPost]
public ActionResult RegisterExpert(FormCollection f)
{

I see all the values... so what am I doing wrong here?


I'm not 100% sure but I would use property instead of public field.

try

public class ExpertsVM
{
    public string GivenName {get;set;}
    public string Surname {get;set;}
}


The model binder looks for public properties on the model. VdesmedT's answer is right, but I am adding this to add emphasis to the point (he wasn't 100% sure, I am).

You could also spare yourself one of the using statments by doing:

@model X.Web.Controllers.ExpertsVM

I have upvoted VdesmedT's answser. You should mark that as the answer.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号