【问题标题】:Ajax.BeginForm() does not hit the ControllerAjax.BeginForm() 没有命中控制器
【发布时间】:2016-03-15 05:59:49
【问题描述】:

下面的代码有一些问题。我有 2 个字段和一个搜索按钮。当我只为字段Holiday 赋值并搜索时,它不会击中控制器。但是,如果我为字段Year 赋值,那么只有它会触发控制器并将两个字段的值都传递给它。

索引.cshtml:

@using (Ajax.BeginForm("Search", "Holiday", new System.Web.Mvc.Ajax.AjaxOptions
       {
           InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace,
           HttpMethod = "POST",
           UpdateTargetId = "holidaylist"
       }))
{                          
    <table>                                
        <tr>                                    
            <td>Holiday: </td>
            <td><input id="searchtext" name="searchtext" type="text" /></td>                           
            <td>Year: </td>
            <td><input id="year" name="year" type="text" />                                                                  </td>                                                                                      
            <td><input type="submit" value="View" id="BtnSubmit" /></td>
        </tr>                            
    </table>                     
}

控制器:

 HttpPost]
 public ActionResult Search(string searchtext, int year)
 {            
     try
     {
         string selyear = year.ToString();

【问题讨论】:

  • 您的控制器的名称是什么?你也有自定义路线吗?
  • 因为参数 year 是 typeof int 并且是必需的(您的控制器将抛出异常。将其更改为 int? year(可为空)

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


【解决方案1】:

这条路线总是期待一年,因为年份不是可选参数。 您可以通过将 year 设为 null 来解决此问题:

 [HttpPost]
 public ActionResult Search(string searchtext, int? year)
    {            
        try
        {
            if (year != null) //you will need to handle the case where year = null
            {
                string selyear = year.ToString();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    相关资源
    最近更新 更多