gpt4 book ai didi

c# - ASP.NET MVC ViewModel 属性为空

转载 作者:行者123 更新时间:2023-11-30 20:19:40 24 4
gpt4 key购买 nike

我有以下 View 模型:

public class ProjectViewModel
{
public Project Project { get; set; }
public Customer Customer { get; set; }
}

Customer 属性仅用于将新的 Project 链接到 Customer,因此我没有在我的 Create View 中包含此属性,如下所示:

@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()

<div class="form-horizontal">
<h4>Project</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Project.Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Project.Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Project.Name, "", new { @class = "text-danger" })
</div>
</div>

<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}

当我发布表单时,我的 ProjectsController 中的以下方法被触发:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Project,Customer")] ProjectViewModel vm)
{
var project = Mapper.Map<Project>(vm);
if (ModelState.IsValid)
{
_db.Create(project);
return RedirectToAction("Index");
}
return View(vm);
}

这是意外行为发生的地方。现在,当我检查 vm 属性时,Customer 属性为 null

问题如何在 View 中不使用 Customer 属性时仍然填充它?

最佳答案

如果您想保留您的客户数据,那么您需要将所有字段设置为隐藏元素,否则它们将在重定向中丢失。

@Html.HiddenFor(model => model.Customer.Property1) ...等...

关于c# - ASP.NET MVC ViewModel 属性为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38332299/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com