[英]Why asp.net model binder can not map a string values to a Object property that have the same name
I have a model class named Server and I have created a new ServerToEdit viewModel class, as follow:- 我有一个名为Server的模型类,我创建了一个新的ServerToEdit viewModel类,如下所示: -
public class ServerToEdit
{
public Server Server { get; set; }
[Required]
public String IPAddress { get; set; }
}
Part of the Create view is:- 创建视图的一部分是: -
model TMS.ViewModels.ServerToEdit
@* This partial view defines form fields that will appear when creating and editing entities *@
@Html.AntiForgeryToken()
<div class="editor-label">
@Html.LabelFor(model => model.Server.CustomerName)
</div>
<div class="editor-field">
@Html.EditorFor(model =>model.Server.CustomerName)
@Html.ValidationMessageFor(model =>model.Server.CustomerName)
</div>
<div class="editor-label">
IP Address
</div>
<div class="editor-field">
@Html.EditorFor(model => model.IPAddress)
@Html.ValidationMessageFor(model => model.IPAddress)
</div>
IPAddress
<div class="editor-label">
@Html.LabelFor(model =>model.Server.ILOIP)
</div>
<div class="editor-field">
@Html.EditorFor(model =>model.Server.ILOIP)
@Html.ValidationMessageFor(model =>model.Server.ILOIP)
</div>
The Create actin method is :- Create actin方法是: -
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Server server, TechnologyIP technologyIP)
{
try
{
if (ModelState.IsValid)
{
repository.InsertOrUpdateServer(server,technologyIP);
repository.Save();
return RedirectToAction("Index");
}
but the model binder was not able to bind the IPAddress field inside my view to the TechnologyIP.IPAddress property? 但模型绑定器无法将我的视图中的IPAddress字段绑定到TechnologyIP.IPAddress属性? the technologyIP model class is :- 技术IP模型类是: -
public class TechnologyIP
{
public String IPAddress { get; set; }
public int ID { get; set; }
}
On first look, I would imagine that it's because the model you passed to the view is not the same model you are asking for back. 初看起来,我会想到这是因为您传递给视图的模型与您要求的模型不同。 Change this line: 改变这一行:
public ActionResult Create(Server server, TechnologyIP technologyIP)
to 至
public ActionResult Create(ServerToEdit serverToEdit)
and this line: 这一行:
repository.InsertOrUpdateServer(server,technologyIP);
to 至
repository.InsertOrUpdateServer(serverToEdit.Server, serverToEdit.technologyIP);
Let us know how you get on. 让我们知道您的身体情况如何。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.