[英]How do I insert data from textbox to model in MVC?`
所以我在MVC中還很陌生,我得到了Mission模型:
public class Mission
{
public ObjectId _id { get; set; }
public string MissionType { get; set; }
public string ElipseNumber { get; set; }
public string MissionDate { get; set; }
public string ReminderNumber { get; set; }
public string Notes { get; set; }
}
當用戶選擇特定任務時,它將以@ViewBag.SelectedMission
進入視圖
現在,我想讓用戶可以選擇向選定的任務添加注釋,因此我使用模態添加了一個文本框,如下所示:
<div class="notesLabel">
@Html.LabelFor(model => model.Notes)
</div>
<div class="notesTextBox">
@Html.TextBoxFor(model => model.Notes)
</div>
不確定確切要怎么做,如何從文本框中獲取輸入並將其添加到SelectedMission.Notes?
感謝前進。
我也是一個初學者,但嘗試提供幫助。 據我了解,您可以執行以下操作
位指示
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Mission model)
{
var notes= model.Notes;
//Set the values to view model accordingly and save to DB eventually
}
視圖
@model Mission
@using (Html.BeginForm("Create", "ControllerName"))
{
@Html.AntiForgeryToken()
// ALL YOUR HTML FIELD WILL COME HERE
<div class="notesLabel">
@Html.LabelFor(model => model.Notes)
</div>
<div class="notesTextBox">
@Html.TextBoxFor(model => model.Notes)
</div>
<input type="submit" value="save">
}
嘗試下面的代碼。 該表格將提交用戶單擊按鈕時輸入的詳細信息。 假設:控制器名稱為Home
,保存注釋數據的動作名稱為SaveNotes
。 當用戶單擊提交按鈕時,數據將發送到HomeController
的SaveNotes
操作。 在動作功能中,完成驗證后,值將保存到DB中。 如果您不想保存到數據庫,則可以按照您的邏輯/設計執行任何操作。 值將在objMission.Notes
。
<% Html.BeginForm("SaveNotes", "Home", FormMethod.Post); %>
@Html.AntiForgeryToken()
:
:
<div class="notesLabel">
@Html.LabelFor(model => model.Notes)
</div>
<div class="notesTextBox">
@Html.TextBoxFor(model => model.Notes)
</div>
:
:
<input type="submit" name="submit" value="Save" />
<% Html.EndForm(); %>
public class HomeController : Controller
{
:
:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveNotes(Mission objMission)
{
//Set the values to view model accordingly and save to DB eventually
if (ModelState.IsValid)
{
db.Missions.Add(objMission);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(objMission);
}
:
:
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.