繁体   English   中英

为什么asp.net模型绑定器无法将字符串值映射到具有相同名称的Object属性

[英]Why asp.net model binder can not map a string values to a Object property that have the same name

我有一个名为Server的模型类,我创建了一个新的ServerToEdit viewModel类,如下所示: -

public class ServerToEdit
    {
        public Server Server { get; set; }
       [Required]
        public String IPAddress { get; set; }
    }

创建视图的一部分是: -

    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>

Create actin方法是: -

[HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(Server server, TechnologyIP technologyIP)
        {
           try 
           { 
               if (ModelState.IsValid) 
           {
                repository.InsertOrUpdateServer(server,technologyIP);
                repository.Save();
                return RedirectToAction("Index");
            }

但模型绑定器无法将我的视图中的IPAddress字段绑定到TechnologyIP.IPAddress属性? 技术IP模型类是: -

public class TechnologyIP
    {
        public String IPAddress { get; set; }

        public int ID { get; set; }
    }

初看起来,我会想到这是因为您传递给视图的模型与您要求的模型不同。 改变这一行:

public ActionResult Create(Server server, TechnologyIP technologyIP)

public ActionResult Create(ServerToEdit serverToEdit)

这一行:

repository.InsertOrUpdateServer(server,technologyIP);

repository.InsertOrUpdateServer(serverToEdit.Server, serverToEdit.technologyIP);

让我们知道您的身体情况如何。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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