[英]MVC3 - Understanding POST with a button
如何在提交后獲取表單數據?
<form target="_self" runat="server">
<p>
<select id="BLAHBLAH2">
<option>2010</option>
<option>2011</option>
<option>2012</option>
<option>2013</option>
</select>
<input type="submit" runat="server" value="Change Year" />
</p>
</form>
這會觸及控制器的Index
方法。 但是, Request.Form
沒有任何內容。 為什么?
其次,我可以使用
<input type="button"
而不是type=submit
? 也就是說,不通過onclick
引入ajax。
最后,如何在控制器中提交不同的方法,例如Create
?
嘗試刪除那些runat服務器標簽。 它們不應該在ASP.NET MVC中使用。 您的選擇也沒有名稱。 如果輸入元素沒有名稱,則不會提交任何內容。 此外,您的選項標簽必須具有值屬性,指示如果選擇此選項將向服務器發送的值:
<form action="/Home/Create" method="post">
<p>
<select id="BLAHBLAH2" name="BLAHBLAH2">
<option value="2010">2010</option>
<option value="2011">2011</option>
<option value="2012">2012</option>
<option value="2013">2013</option>
</select>
<input type="submit" value="Change Year" />
</p>
</form>
但是在ASP.NET MVC中生成表單的正確方法是使用HTML幫助程序。 根據您使用的視圖引擎,語法可能會有所不同。 以下是Razor視圖引擎的示例:
@model MyViewModel
@using (Html.BeginForm("Create", "Home"))
{
<p>
@Html.DropDownListFor(x => x.SelectedYear, Model.Years)
<input type="submit" value="Change Year" />
</p>
}
這里有一個給定視圖模型的強類型視圖:
public class MyViewModel
{
public string SelectedYear { get; set; }
public IEnumerable<SelectListItem> Years
{
get
{
return Enumerable
.Range(2010, 4)
.Select(x => new SelectListItem
{
Value = x.ToString(),
Text = x.ToString()
});
}
}
}
由一些將呈現此視圖的控制器操作填充:
public class HomeController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel();
return View(model);
}
[HttpPost]
public ActionResult Create(MyViewModel model)
{
... model.SelectedYear will contain the selected year
}
}
您的<option>
標簽都沒有值:
...
<option value="2010">2010</option>
...
正如David所說,runat =“server”絕對是WebForms的東西,所以你可以86。
如果要在控制器上提交不同的方法,只需指定該方法的URL即可。
使用Html.BeginForm的簡單方法:
@using (Html.BeginForm("AnotherAction", "ControllerName")) {
<!-- Your magic form here -->
}
<form action="@Url.Action("AnotherAction")" method="POST">
<!-- Your magic form here -->
</form>
您也可以使用In Controller
int Value = Convert.ToInt32(Request["BLAHBLAH2"]); //To retrieve this int value
在.cshtml文件中使用
<select id="IDxxx" name="BLAHBLAH2">
// Request [“”]將檢索html對象的VALUE,其請求的“名稱”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.