视图模型从主创建视图传递到控制器 Null



我知道这个问题已经被问了很多次,但用我的代码检查了所有答案,我没有命名冲突,我将 ID 作为隐藏字段传递,但 ViewModel 作为空传递给控制器。

这个问题是我的项目想法和代码片段的链接。我可能错过了什么?

我创建了一个新项目并将您的代码复制到项目中。我在尝试创建时也收到了一个空模型。为我修复它需要一些更改。我不得不将"Model.AccountOrOU"作为传递到部分的模型。我必须在控制器中初始化创建索引的模型。我还必须更改视图中 AccountOrOU 模型属性的名称属性。这是我的代码->

Index.cshtml

@model AccountVM
@{
ViewData["Title"] = "Home Page";
}
<h2>Create</h2>
@using (Html.BeginForm("SaveAccount", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
<div>
@{await Html.RenderPartialAsync("_Account.cshtml", Model.AccountOrOU);}
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" />
</div>
</div>
</div>
}

_Account.cshtml

@model AccountOrOU
<div class="form-horizontal" id="ViewData">
<h4>Account Partial</h4>
<hr />
<div class="form-group">
@Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="text" name="AccountOrOU.Name" class="form-control" />
</div>
</div>
</div>

<div>
@Html.ActionLink("Back to List", "Index")
</div>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Test2.Models
{
public class AccountVM
{
public AccountVM()
{
AccountOrOU = new AccountOrOU();
}
public AccountOrOU AccountOrOU { get; set; }
}
public class AccountOrOU
{
public string Name { get; set; }
}
}

控制器

public IActionResult Index()
{
AccountVM blah = new AccountVM();
return View(blah);
}
public IActionResult SaveAccount(AccountVM input)
{
return View("Index", input);
}

看看这是否有帮助:

@{await Html.RenderPartialAsync("_Account.cshtml"}

然后更改此行:

<input type="text" name="AccountOrOU.Name" class="form-control" />

对此:

@Html.TextBoxFor(x => x.AccountOrOU.Name, new { @class="form-control" })

最新更新