【问题标题】:AJAX.BeginForm send empty FormCollection list to MVC ControllerAJAX.BeginForm 向 MVC 控制器发送空的 FormCollection 列表
【发布时间】:2012-07-16 19:43:10
【问题描述】:

我有一个非常简单的代码:

@using (Ajax.BeginForm("SearchAccount", "Account", new AjaxOptions { UpdateTargetId = "SearchResults", HttpMethod = "Get", InsertionMode = InsertionMode.Replace })) 
    {
        <fieldset>
            <input id="txtSearchBox" name="SearchString" type="text"  />
        </fieldset>
        <input type="submit" value="Search"  />
    }

在控制器端我有以下代码

public PartialViewResult SearchAccount(FormCollection formCollection)
    {
        try
        {
            string SearchString = formCollection["SearchString"];
            List<Moovers.DAL.Account> Accounts = Moovers.BL.Account.SearchAccount(SearchString);

            return PartialView("_AccountSearchResult", Accounts);        
        }
        catch (Exception ex)
        {
            throw;
        }

    }

问题是“FormCollection”,它是空的。可能的原因是什么?

【问题讨论】:

    标签: asp.net ajax asp.net-mvc-3 ajax.beginform formcollection


    【解决方案1】:

    为什么要使用FormCollection?你可以直接把SearchString作为action参数吧?

    public PartialViewResult SearchAccount(string SearchString)
    {
      try
      {
         var Accounts = Moovers.BL.Account.SearchAccount(SearchString);
         return PartialView("_AccountSearchResult", Accounts);        
      }
      catch (Exception ex)
      {
         throw;
      }
    }
    

    如果您从 Form 传递多个值,那么您可以创建一个视图模型并简化您的生活。

    例如

    public class SearchModel
    {
       public string SearchString { get; set; }
       .. others
    }
    
    public PartialViewResult SearchAccount(SearchModel searchModel)
    {
      ...
    }
    

    注意,重要的是表单字段的名称应该与参数/属性名称匹配。

    【讨论】:

      【解决方案2】:

      这是因为您使用"GET" 作为您的方法。

      https://stackoverflow.com/a/2265210/120955

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-12-05
        • 2020-04-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多