Why is an empty Model returning to post method?
Ok, a similar question has being posted but I'm not seeing an answer that would apply to this scenario or the more likely, I'd fully understand the answer !
Basically I have a get ViewResult and Post ActionResult , the Get returns the correct model but when submitting, the model returns all properties as null ? Have user similar code in other methods and it works, can anyone see the problem ? Still learning , so please explain any answer, thanks.
[HttpGet]
public ViewResult DeleteUser(string username)
{
IQueryRunner<User> getUser = new NhQueryRunner<User>();
User user = getUser.GetQueryResult(new GetNamedEntity<User>(username));
ViewUserModel model = Mapper.Map<User, ViewUserModel>(user);
return View("DeleteUser", model);
}
[HttpPost]
public ActionResult DeleteUser(ViewUserModel model)
{
}
View
@using (Html.BeginForm("DeleteUser", "Company", FormMethod.Post))
{
<fieldset>
Are you sure you want to delete Username - @Html.DisplayFor(m => m.Name)
<input type="submit" value="Remove User"/>
</fieldset>
}
Form submits values from it's inputs. You don't have inputs with names equal to your model properties names, so submitted form data does not contain these values. Other value providers (query string, route data, etc) also don't have values corresponding to model properties. So, model binder cannot bind values and you have all properties of your model equal to null
(which are reference type properties).
You can use @Html.HiddenFor(m => m.Name)` as suggested by @Michael to generate hidden input in your form:
<input id="Name" type="hidden" value="username_value" name="Name">
Now if you'll check Request.Form
values collection, it will contain entry with key Name
and username_value
value. FormValueProvider
provides access to this collection to model binder. And property with name Name
will be bound successfully.
You're getting an empty model because there are no input
controls for the properties on the model in the form. Even the DisplayFor
won't send a value back in the POST
. I would recommend doing this:
@Html.HiddenFor(m => m.Property1)
@Html.HiddenFor(m => m.Property2)
@Html.HiddenFor(m => m.Property3)
...
where Property{n}
are the properties on the model.
You need to have a form input element in your form section so that the browser can post back to the server. Update your code and add the following property
@using (Html.BeginForm("DeleteUser", "Company", FormMethod.Post))
{
<fieldset>
Are you sure you want to delete Username - @Html.DisplayFor(m => m.Name)
@Html.HiddenFor(x=>x.Name)
<input type="submit" value="Remove User"/>
</fieldset>
}
链接地址: http://www.djcxy.com/p/53968.html
上一篇: 如何根据选中的复选框将列表返回给控制器?
下一篇: 为什么空模型返回post方法?