2011-10-07 51 views
5

如何在提交表單後獲取表單數據?MVC3 - 通過按鈕瞭解POST

<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

+3

是不是'runat =「server」'一個webforms的東西? –

回答

7

嘗試刪除這些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 
    } 
} 
+0

我用剃刀更新了我的問題。儘管我可以很容易地進行翻譯。 –

+0

@ P.Brian.Mackey,我用Razor的例子更新了我的答案。 –

+0

@DarinDimitrov - 我向你的詳細程度屈服:) – Josh

2

<option>任何標籤有值:

... 
<option value="2010">2010</option> 
... 

正如David指出,RUNAT = 「服務器」 是最絕對是一個東西的WebForms,這樣你就可以86。

如果您想在控制器上提交不同的方法,您只需指定該方法的URL即可。使用Html.BeginForm

簡單的方法:

@using (Html.BeginForm("AnotherAction", "ControllerName")) { 
    <!-- Your magic form here --> 
} 

使用Url.Action

<form action="@Url.Action("AnotherAction")" method="POST"> 
    <!-- Your magic form here --> 
</form> 
+0

謝謝,很高興看到替代方案來完成任務。 –

0

您還可以使用 在控制器

int Value = Convert.ToInt32(Request["BLAHBLAH2"]); //To retrieve this int value 

在.cshtml文件中使用

<select id="IDxxx" name="BLAHBLAH2"> 

//請求(「」)將檢索的HTML對象,其值「名」您請求。