我有一个用于创建包含大量文本框的客户的视图。在用户选中每个文本框后,我想使用JQuery调用一个Controller方法,该方法将检查DataBase并查找任何可能的匹配,然后控制器将发送内容,我将使用jQuery动态显示可能的匹配(类似当你输入你的问题并显示相关问题时,Stack Overflow会做什么。
我的问题是,我有15个文本框,并且希望每次调用都从每个背面发送数据。我想避免让我的Controller方法具有像
这样的签名Public ActionResult CheckMatches(string param1, string param2... string param15)
是否有更简单的方法将多个参数作为单个对象传递,如FormCollection?
答案 0 :(得分:3)
您需要做的就是创建一个类型与文本框名称相同的类型:
public class CheckMatchesAguments
{
public string Param1 { get; set; }
public string Param2 { get; set; }
// etc.
}
然后将您的操作更改为:
public ActionResult CheckMatches(CheckMatchesAguments arguments)
这就是全部!
但请注意:如果CheckMatchesAguments具有任何不可为空的属性(例如,int),那么的值必须必须在FormCollection中,否则默认模型绑定器将不会绑定任何内容在类型中。要解决这个问题,要么在表单中包含这些属性,要么使属性可以为空。
答案 1 :(得分:0)
Javascript:
var data = { foo: "fizz", bar: "buzz" };
$.get("urlOfAction", data, callback, "html")
动作:
public ActionResult FooAction(MegaParameterWithLotOfStuff param)
自定义model binder:
public class MegaParameterWithLotOfStuffBinder : IModelBinder
{
public object GetValue(ControllerContext controllerContext,
string modelName, Type modelType,
ModelStateDictionary modelState)
{
var param = new MegaParameterWithLotOfStuff();
param.Foo = controllerContext.
HttpContext.Request.Form["foo"];
param.Bar = controllerContext.
HttpContext.Request.Form["bar"];
return customer;
}
}
Global.asax:
protected void Application_Start()
{
ModelBinders.Binders[typeof(MegaParameterWithLotOfStuff)] =
new MegaParameterWithLotOfStuffBinder();
}
或绑定过滤器+动作组合:
public class BindMegaParamAttribute: ActionFilterAttribute
{
public override void OnActionExecuting
(ActionExecutingContext filterContext)
{
var httpContext = filterContext.HttpContext;
var param = new MegaParameterWithLotOfStuff();
param.Foo = httpContext.Request.Form["foo"];
param.Bar = httpContext.Request.Form["bar"];
filterContext.ActionParameters["param"] = param;
base.OnActionExecuted(filterContext);
}
}
行动:
[BindMegaParam]
public ActionResult FooAction(MegaParameterWithLotOfStuff param)