简体   繁体   中英

Null model passed in MVC to controller when form is submitted

I am using MVC4 application, and there is one controller for allowing user to input some data. The thing is I am getting null values in all the properties returned from the form. I am using strongly typed model and I did not see any name collisions as suggested in few posts about null model being passed. Heres my Model

public class NewsItemView
{

    [Required]
    public string NewsTitle;

    public string NewsAuthor;

    public string NewsSummary;

    public string NewsDescription;

    public bool NewsAllowComments;

    [Required]
    public string NewsContent;

    public string NewsSourceName;
}

Controller Action(get)

    [HttpGet]
    public ActionResult Create()
    {
        NewsItemView nv = new NewsItemView();
        return View(nv);
    }

View:

@model NewsItemView

@using (Html.BeginForm("Create", "Service", FormMethod.Post, new { @id = "NewsForm" }))
{
@Html.LabelFor(model => model.NewsTitle)
@Html.EditorFor(model => model.NewsTitle)
<br />
@Html.LabelFor(model => model.NewsAuthor)
@Html.EditorFor(model => model.NewsAuthor)
<br />
@Html.LabelFor(model => model.NewsAllowComments)
@Html.EditorFor(model => model.NewsAllowComments)
<br />
@Html.LabelFor(model => model.NewsSummary)
@Html.EditorFor(model => model.NewsSummary)
<br />
@Html.LabelFor(model => model.NewsDescription)
@Html.EditorFor(model => model.NewsDescription)
<br />
@Html.LabelFor(model => model.NewsContent)
@Html.EditorFor(model => model.NewsContent)
<br />
@Html.LabelFor(model => model.NewsSourceName)
@Html.EditorFor(model => model.NewsSourceName)

<br />

<button type="submit" id="submitBtn">Create News</button>

}

Controller Action(post)

    [HttpPost]
    public ActionResult Create(NewsItemView newsModel)
    {
     //my code here
    }

If i use FormsCollection, I am able to extract the values using index, any idea why the strongly typed model is not working?

I have reproduced the issue on my environment and all what I have done to fix it is just updating the model fields to be properties like the following

public class NewsItemViewModel
{

    [Required]
    public string NewsTitle { get; set; }

    public string NewsAuthor { get; set; }

    public string NewsSummary { get; set; }

    public string NewsDescription { get; set; }

    public bool NewsAllowComments { get; set; }

    [Required]
    public string NewsContent { get; set; }

    public string NewsSourceName { get; set; }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM