2016-04-21 26 views
0

在Asp.net MVC视图中,我创建了一个带有输入字段的表单。Asp.net MVC - 表单不发送给控制器

用户设置名字(或其中的一部分),按下提交按钮。

这是形式部分:

<div> 
    <form action="SearchCustomer" methos="post"> 
     Enter first name: <input id="Text1" name="txtFirstName" type="text" /> 
     <br /> 
     <input id="Submit1" type="submit" value="Search Customer" /> 
    </form> 
</div> 

这是SearchCustomer在控制器,从所述表格获取数据:

CustomerDal dal = new CustomerDal(); 
string searchValue = Request.Form["txtFirstName"].ToString(); 
List<Customer> customers = (from x in dal.Customers 
          where x.FirstName.Contains(searchValue) 
          select x).ToList<Customer>(); 
CustomerModelView customerModelView = new CustomerModelView(); 
customerModelView.Customers = customers; 

return View("ShowSearch", customerModelView); 

当运行该程序,并进入第一名称(例如“Jhon”),代码返回到SearchCustomer函数,但Request.Form为空。

为什么?

谢谢。

+4

错字!..而不是'methos = “POST”'应该是'方法= “邮报”' –

+1

并且在表单动作不动作叫什么名字? –

+1

由于@KartikeyaKhosla提到,你有一个错误的'methos'应该是方法,并且你的动作应该采用以下格式:YourControllerName/YourActionName –

回答

1

您需要修改代码:

你需要在这里提供一个动作名称,它应该在你的控制器(SearchController)具有相同的名称为“ActionName”来定义你将放在下面的代码。 如果SearchController是您的操作名称,则提供操作可用的控制器。

<div> 
    <form action="SearchCustomer/<ActionName>" method="post"> 
     Enter first name: <input id="Text1" name="txtFirstName" type="text" /> 
     <br /> 
     <input id="Submit1" type="submit" value="Search Customer" /> 
    </form> 
</div> 

随着Html.BeginForm:

@using (Html.BeginForm("<ActionName>","<ControllerName>", FormMethod.Post)) 
    { 
     Enter first name: <input id="Text1" name="txtFirstName" type="text" /> 
     <br /> 
     <input id="Submit1" type="submit" value="Search Customer" /> 
    } 
+3

这种方法很可能会以另一个404结束。一般而言,应该使用Url.Action()或Html.BeginForm()来代替或硬编码路径。 – haim770

+0

@ Zag如果这对你有用,你可以将它标记为已接受,谢谢。 – sumngh

0

method拼写错了不应该读methosmethod象下面这样:

<form action="SearchCustomer" method="post"> 
      .... 
    </form> 
0

如果View是相同的名称ActionResult方法,试试这个:

@using(Html.BeginForm()) 
{ 
    ... enter code 
} 

默认情况下,它将是一个POST方法类型,它将被定向到ActionResult。有一两件事要确保的:你需要在你的ActionResult方法[HttpPost]属性,这样的形式知道去哪里:

[HttpPost] 
public ActionResult SearchCustomer (FormCollection form) 
{ 
    // Pull from the form collection 
    string searchCriteria = Convert.ToString(form["txtFirstName"]); 
    // Or pull directly from the HttpRequest 
    string searchCriteria = Convert.ToString(Request["txtFirstName"]); 
    .. continue code 
} 

我希望这有助于!

0

在控制器上设置[HttpPost]。

[HttpPost] 
public ActionResult SearchFunction(string txtFirstName) 
    { 
      CustomerDal dal = new CustomerDal(); 
     string searchValue = txtFirstName; 
     List<Customer> customers = (from x in dal.Customers 
          where x.FirstName.Contains(searchValue) 
          select x).ToList<Customer>(); 
     CustomerModelView customerModelView = new CustomerModelView(); 
     customerModelView.Customers = customers; 
     return View("ShowSearch", customerModelView); 
    } 
+0

我的推特处理程序:@ mohitdagar80 –

相关问题