gpt4 book ai didi

asp.Net MVC View 模型在帖子中为空

转载 作者:行者123 更新时间:2023-12-02 12:15:34 25 4
gpt4 key购买 nike

我有一个复杂的 View 模型,我正在将其传递给创建 View 。当我在页面上输入数据并将其发布时,模型是空的。子对象中的字段和“测试”字段均为空。为什么?

public class ContactIncident
{
[Key]
public int Id { get; set; }

[DataType(DataType.MultilineText)]
public string Description { get; set; }

[Display(Name = "Incident Date")]
[DataType(DataType.Date)]
public DateTime? IncidentDateTime { get; set; }

[Display(Name = "Follow Up Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[DataType(DataType.Date)]
public DateTime? FollowUpDate { get; set; }
}

public class IncidentManager
{
public ContactIncident Incident { get; set; }
public string Test { get; set; }
}


public ActionResult Create(int? id)
{
IncidentManager im = new IncidentManager();
ContactIncident ci = new ContactIncident();
ci.IncidentDateTime = DateTime.Now;
ci.FollowUpDate = DateTime.Now.AddDays(14);
im.Incident = ci;
return View(im);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(IncidentManager im)
{
if (ModelState.IsValid)
{
ContactIncident ci = new ContactIncident();
ci.IncidentDateTime = incident.Incident.IncidentDateTime;
ci.Description = im.Incident.Description;
return RedirectToAction("Index");
}
return View(incident);
}

查看:

@model MyApp.Web.ViewModels.IncidentManager
@{
ViewBag.Title = "Edit Incident";
}
<h4>@ViewBag.Title</h4>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal well">
@Html.ValidationSummary(true)
@Html.EditorFor(model=>model.Test)
<div class="row">
<div class="col-md-2">
@Html.LabelFor(model => model.Incident.IncidentDateTime)
</div>
<div class="col-md-2">
@Html.DisplayFor(model => model.Incident.IncidentDateTime)
</div>
</div>
<div class="row">
<div class="col-md-2">
@Html.LabelFor(model => model.Incident.Description)
</div>
<div class="col-md-10">
@Html.EditorFor(model => model.Incident.Description, new { htmlAttributes = new { @class = "form-control", rows = "5" }, })
</div>
<div class="col-md-2">
@Html.LabelFor(model => model.Incident.FollowUpDate)
</div>
<div class="col-md-2">
@Html.EditorFor(model => model.Incident.FollowUpDate, new { htmlAttributes = new { @class = "form-control"}, })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
}

最佳答案

问题是 DefaultModelBinder如果您使用不同的参数名称,将无法正确映射嵌套模型。您必须使用与 ViewModel 名称相同的参数名称

public ActionResult Create(IncidentManager incidentManager)

作为一般做法,请始终使用模型名称作为参数名称,以避免映射问题。

更新:

DefaultModelBinder 使用“基于约定”的映射。

IncidentManager.Incident = incidentManager.Incident (will map)
IncidentManager.Incident = im.Incident //won't map because 'im' != 'incidentManager'

关于asp.Net MVC View 模型在帖子中为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24939054/

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