【发布时间】:2017-12-08 07:03:22
【问题描述】:
我的 ViewModel 总是返回 null 并且不知道为什么。有人可以查看我的代码并检查这里有什么问题以及为什么我的填充模型与视图中的数据以null 的形式返回到控制器吗?
public class PaintballWorkerCreateViewModel
{
public PaintballWorker PaintballWorker { get; set; }
public PaintballWorkerHourlyRate HourlyRate { get; set; }
}
控制器
public ActionResult Create()
{
PaintballWorkerCreateViewModel model = new PaintballWorkerCreateViewModel()
{
PaintballWorker = new PaintballWorker(),
HourlyRate = new PaintballWorkerHourlyRate()
{
Date = DateTime.Now
}
};
return View(model);
}
[HttpPost]
[PreventSpam(DelayRequest = 20)]
[ValidateAntiForgeryToken]
public ActionResult Create(PaintballWorkerCreateViewModel paintballWorker)
{
(...)
}
查看,甚至添加了 HiddenFor ID(不是在控制器的 GET 函数中创建的)。
@model WerehouseProject.ViewModels.PaintballWorkerCreateViewModel
@{
ViewBag.Title = "Utwórz pracownika";
Layout = "~/Views/Shared/_Layout_Paintball.cshtml";
}
<h2>Dodawanie pracownika</h2>
@using (Html.BeginForm("Create", "PaintballWorkers", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.PaintballWorker.Active)
@Html.HiddenFor(model => model.PaintballWorker.MoneyGot)
@Html.HiddenFor(model => model.PaintballWorker.PaintballWorkerID)
@Html.HiddenFor(model => model.HourlyRate.Date)
@Html.HiddenFor(model => model.HourlyRate.PaintballWorkerID)
@Html.HiddenFor(model => model.HourlyRate.PWHourlyRateID)
<div class="form-group">
@Html.LabelFor(model => model.PaintballWorker.Imie, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.PaintballWorker.Imie, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.PaintballWorker.Imie, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.PaintballWorker.Nazwisko, htmlAttributes: new { @class = "control-label col-md-2" })
(...)
<div class="form-group">
@Html.LabelFor(model => model.HourlyRate.HourlyRate, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.HourlyRate.HourlyRate, new { htmlAttributes = new { @class = "form-control", @type = "number", @min = "0.1", @step = "0.1", @value = "10" } })
@Html.ValidationMessageFor(model => model.HourlyRate.HourlyRate, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Dodaj pracownika" class="btn btn-primary" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Powrót do listy", "Index", new object { }, new { @class = "btn btn-default" })
</div>
【问题讨论】:
-
是所有值都为空还是只有几个值?
-
PaintballWorker和HourlyRate为空,即使我创建模型并用GET函数中的数据填充它。 -
你能显示这两个类的代码吗?
-
你是说连 GET 函数都为空?视图没有填充这些值吗?
标签: c# asp.net-mvc null viewmodel