[英]How to call a method from controller when a button from form is pressed?
主要問題是,當我按下按鈕時,不會調用控制器的方法。 我在MyController的索引視圖中有這個:
@using (Html.BeginForm())
{
@* .... *@
<form action="DoSomethingAction" method="post">
<input type="text" id="IdString" name="IdString" placeholder="Enter id"/>
<input id="Submit1" name="Submit1" type="submit" value="DoSomething1" />
<input id="Submit2" name="Submit2" type="submit" value="DoSomething2" />
</form>
@* ..... *@
}
在MyController中,我有DoSomethingAction方法。 我想調用此方法,並在按以下按鈕時看到IdString:DoSomething1或DoSomething2。 這是來自控制器的DoSomethingAction方法:
public ActionResult DoSomethingAction()
{
string id= Request.Form["IdString"];
//string button=...
// ...
}
當我為DoSomethingAction方法設置一個斷點時,我發現它從未被調用過。 我嘗試為該方法設置[Httppost]屬性,但並不能解決我的問題。
我究竟做錯了什么? 之后,如何在DoSomethingAction方法中看到按下了哪個按鈕?
HTML表單不能嵌套HTML表單。 請閱讀https://www.w3.org/TR/html5/forms.html#the-form-element
如果需要多種形式,可以將它們定義為同級。
使用html.BeginForm
或type="Submit"
。 接下來要記住的是html.BeginForm
是一個post方法,因此,如果您要使用它,請在Action上賦予一個屬性,如果您不聲明應返回的view
操作,他將假定該視圖具有相同的視圖名稱為動作,在您的情況下為DoSomethingAction
,這就是為什么您會收到服務器錯誤。 使該視圖或在return View()
中聲明您要返回的視圖(索引或其他某個視圖)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.