[英]How to pass input value from the form which is not part of any model?
在剃刀視圖中,我有一個表格:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Person</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(model => model.Id)
<div class="form-group">
@Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
</div>
</div>
等長時間,但我想將以下這些值傳遞給控制器:
<div class="form-group">
<input class="form-control text-box single-line valid" id="FetchDate" name="FetchDate" type="date">
<input class="form-control text-box single-line valid" id="FetchTime" name="FetchTime" type="time">
</div>
<div class="form-group">
<div class="col-md-offset-0 col-md-10">
<input type="submit" value="Save" class="btn btn-default" style="width: 200px; font-weight: bold;" />
</div>
</div>
</div>
}
Submit(type="submit)
按鈕在Person
控制器中調用POST
編輯操作:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,FirstName")] Person person) {
if (ModelState.IsValid) {
db.Entry(person).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
我們可以看到,唯一的參數是Person person
,但是在表單中我添加了兩個與Person沒有共同點的字段,但是我還想將它們中的值傳遞給提交按鈕POST Edit
:
<div class="form-group">
<label class="control-label col-md-2" >If you want this client to be fetched to you later, fullfil the data.</label>
<input class="form-control text-box single-line valid" id="FetchDate" name="FetchDate" type="date">
<input class="form-control text-box single-line valid" id="FetchTime" name="FetchTime" type="time">
</div>
問題:如何將值傳遞到控制器的POST Edit
操作中,這些值不屬於我的Razor視圖(上圖)中的任何模型?
我試過了,時間為null或空字符串(尚未檢查):
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,FirstName")] Person person, [Bind(Include="FetchTime")] String time) {
Debug.WriteLine("Time " + time);
if (ModelState.IsValid) {
db.Entry(person).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
你可以這樣做:
public ActionResult Edit([Bind(Include = "Id,FirstName")] Person person, string FetchDate, string FetchTime) {
if (ModelState.IsValid) {
db.Entry(person).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(person);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.