【发布时间】:2016-05-08 11:41:26
【问题描述】:
我正在使用 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);
}
【问题讨论】:
-
你有什么问题?您的 POST 方法有一个参数
ClientDateTime,它将包含隐藏输入的值 -
我遇到的问题是,我收到的控制器值是文本:ClienntDateTime 而不是实际值(即“06/05/2016 20:36)。谢谢
-
从您的
BeginForm()方法中删除new { ClientDateTime = "ClientDateTime" }。只需使用@Html.Hidden("ClientDateTime")- 尝试将id属性设置为与它已经存在的值完全相同的值是没有意义的。然后扔掉所有这些,并使用视图模型正确地完成它。 -
你说得对,我从 BeginForm() 方法中删除了 new { ClientDateTime = "ClientDateTime" },现在我可以在我的控制器中访问 ClientDateTime。谢谢你的帮助:)
-
你的脚本可以是
document.getElementById('ClientDateTime').value = new Date().toISOString();,你的方法中的参数应该是DateTime ClientDateTime(不是string)
标签: asp.net asp.net-mvc-5 html.beginform