MVC表单不是控制器方法

时间:2015-10-01 14:17:59

标签: c# asp.net-mvc asp.net-mvc-4

我是mvc的新手,所以我仍在努力解决一些问题。 我有一个非常简单的形式和控制器。 控制器:

    public class InquiryController : BaseController {

    public ActionResult Index() {

        return View();
    }

    public ActionResult Search(int Id) {

         int newid = Id;

        return View();

    }
}

和表格:

@using (Html.BeginForm("Index", "Results", FormMethod.Post))
{
    @Html.TextBox("id", null, new { type = "Search", autofocus = "true", style = "width: 200px" })
    <input type="submit" value="Search" />
}

当我在表单中输入数字时,我希望将该数字传递给控制器​​中的“搜索”功能。我不明白如何让表单调用控制器并在该控制器内进行处理。相反,它会查找“结果”页面时出错,我理解它来自BeginForm方法。 所以从本质上讲,我如何让我的表单将输入搜索框的数字传递给我的控制器函数?

2 个答案:

答案 0 :(得分:6)

Html.BeginForm的前两个参数中指定要进入的操作和控制器。

@using (Html.BeginForm("Search", "Inquiry", FormMethod.Post))
{
    @Html.TextBox("id", null, new { type = "Search", autofocus = "true", placeholder = "Harvest Tag, 6 Digit Tag No.", style = "width: 200px" })
    <input type="submit" value="Search" />
}

在操作中,您可以像访问的那样访问ID,但您也可以从FormCollection["id"]Request["id"]获取该ID作为原始字符串并对其进行验证,以避免出现解析错误用户提交无效的int。

答案 1 :(得分:2)

BeginForm的第一个参数是要执行的操作,第二个参数是要执行的控制器,因此您的使用应该是:

@using (Html.BeginForm("Search", "Inquiry", FormMethod.Post))

通过输入控件的HTML ID(id)找到传入的值(在本例中)