I have the following page :
<form method="post">
<hr />
<h4>Alert</h4>
<div class="card-overview">
<div class="card-columns">
<partial name="_Alert" model="Model.Details.AlertPageModel" />
</div>
</div>
My partial view looks as follows:
@model AlertPageModel
<div class="card">
<div class="card-body">
@Html.TextBox("AlertPageModel.AlertDate", Model.AlertDate)
@Html.TextBox("AlertPageModel.Message", Model.Message)
</div>
This results in my partial view as follows:
<input id="AlertPageModel_Message" name="AlertPageModel.Message" type="text" value="">
<input id="AlertPageModel_AlertDate" name="AlertPageModel.AlertDate" type="text" value="24/06/2019 10:23:12">
Now when I do a post of the page, my AlerPageModel remains empty. I thought it would get filled this way. What am I missing?
The name of the element is mapped to the property in the model when form is posted back. It looks like the names are not correct. You will need to specify the TextBox name like following so that it is posted in the property :
@Html.TextBox("Details.AlertPageModel.AlertDate", Model.AlertDate)
@Html.TextBox("Details.AlertPageModel.AlertPageModel.Message", Model.Message)
As your model AlertPageModel
is a property of Details
property in your main Model class we need to specify the name correctly so that it gets mapped to proper Model object and Model Binder can figure out that this value needs to be mapped on which particular property in the Model object.
Alternatively you can use EditorFor
and define an editor template instead of partial which takes care of prefixing the proper name so that it is properly binded in the form post. You may read more about this at following post:
https://www.codeproject.com/Articles/1079909/ASP-NET-MVC-Partial-Views-with-Partial-Models
Hope it makes sense.
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.