控制器:
public ActionResult Index()
{
whateverModel d = new whateverModel();
return View(d);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(whateverModel m)
{
if (ModelState.IsValid)
{
//its valid, update your database or do soemthing useful here
return RedirectToAction("Success");
}
//its not valid reload the page and let data annotations show the error
return View(m);
}
一旦你在控制器代碼,那麼你可以有Visual Studio中自動創建視圖。在您的控制器中,右鍵單擊「d」返回View(d);並選擇「添加視圖」。將模板更改爲「創建」和Model類到您的模型(在本例中爲whateverModel)。它會自動爲您導入生成的chtml頁面,導入的模型和已經爲您生成的編輯器。下面的示例自動生成視圖。你可以在造型等方面工作。
CSHTML:
@model YourSolution.Models.whateverModel
@{
ViewBag.Title = "Whatever";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Whatever</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Whatever</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.FriendlyName, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.FriendlyName, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.FriendlyName, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.Order, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Order, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Order, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
如果你只是想輸出用戶提交的內容,那麼在MVC中有很多方法可以做,如果你想在保存字段的新視圖中的確認消息,在你的db.SaveChanges之後,你可以做一個返回RedirectToAction(「ComfirmationView」,yourModel),然後將其傳遞給一個ActionResult Comfirmation(YourModel yourModel) – Henry24
我認爲你有點混淆,我將這個問題改寫。刪除了所有不必要的細節。請檢查 – maverick
您應該使用'@model YourModel',您將此代碼添加到視圖的頂部,或者當您添加視圖時,有一個選項可以創建強類型視圖,選中此選項並在模型類下選擇您的模型類。 [閱讀更多](https://docs.microsoft.com/zh-cn/aspnet/mvc/overview/older-versions/mvc-music-store/mvc-music-store-part-3) – Munzer