2011-10-07 54 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对象,其值“名”您请求。