MVC3 - Insert using ViewModel - Object reference not set to an instance of an object

做~自己de王妃 提交于 2019-12-03 23:43:39

Simply rename your action argument:

public ActionResult Create(BlogViewModel viewModel)

There is a conflict because your action argument is called blog and yet your view model (BlogViewModel) has a property called Blog. The problem is that the default model binder no longer knows what to do in such situation.

Oh and if you absolutely need to have your action argument called blog then you could also rename the Blog property on your view model.

I have ran in these kinds of situation before. This happens, when the data that you are sending from your view is not in a format, that MVC default model binding engine can understand or can map to your view model object. Try using "FireBug" and see as how the data is being passed via POST. And then see, if that data can be mapped to the definition of your view model.

One more thing, are you using jQuery to pass the data or you are using explicit view model based interaction between your views and controller ?

@Michael Willmott

Although this topic is 6 years old but i find out it useful for a scenario I have dealt with recently.

In my MVC view, instead using a full path for identifiers, I used inline short cut variable with Razor and that caused the postback view model to server was null. That was because the "name" and "id" attributes for html elements were not rendered correctly as MVC binding mechanism expects:

The following is wrong declaration:

@{
   var b = Model.Blog; // short cut caused problem of postback model binding
}

<div class="editor-field">
            @Html.EditorFor(model => b.Title)
            @Html.ValidationMessageFor(model => b.Title)
        </div>

The following is correct declaration as full path for identifiers is needed:

<div class="editor-field">
            @Html.EditorFor(model => model.Blog.Title)
            @Html.ValidationMessageFor(model => model.Blog.Title)
        </div>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!