我使用BeginForm传递模型数据(即last_coffe_time),这很好。然而,我也想将存储在隐藏字段中的ClientDateTime值传递给控制器,该字段不是模型的一部分。我不知道该怎么做,充其量我可以将ClientDateTime作为静态字符串传递,但我不知道如何动态读取值的隐藏字段并将该值传递给控制器。
有人请帮忙。谢谢
视图:
@model SleepNotes.Models.Diary
@using (Html.BeginForm("Edit", "Diary", new { ClientDateTime = "ClientDateTime" }, FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
@Html.Hidden("ClientDateTime", new { id = "ClientDateTime" })
<div class="form-group">
@Html.LabelFor(model => model.last_coffe_time, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.last_coffe_time, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.last_coffe_time, "", new { @class = "text-danger" })
</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>
</div>
}
<!--Set ClientDateTime-->
<script>
var a = new Date()
var month = a.getMonth() + 1;
document.getElementById('ClientDateTime').value = a.getDate() + "/" + month + "/" + a.getFullYear() + " " + a.getHours() + ":" + a.getMinutes() + ":" + a.getSeconds();
</script>
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "id,last_coffe_time")] Diary Diary, string ClientDateTime)
{
if (ModelState.IsValid)
{
//ClientDateTime from view ...do something here
db.Entry(Diary).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index", "Dashboard");
}
return View(Diary);
}
从BeginForm()
方法中删除new { ClientDateTime = "ClientDateTime" }
,这样该值就不会作为路由参数添加(因此不会绑定到Edit()
方法中的string ClientDateTime
参数。
附带说明:由于您想要提交DateTime
值,您的参数应该是DateTime ClientDateTime
(而不是string
),并且您的脚本可以简化为
document.getElementById('ClientDateTime').value = new Date().toISOString();
有一些解决方案,
- 我建议您在Model和View之间使用ModelView。那个modalview应具有ClientDateTime
- 您可以使用ajax post并将2个参数(yourmodal,string)发送到控制器或可以将ClientDateTime作为查询字符串传递。有很多关于它的例子
希望有帮助。