[英]ASP.NET MVC Model Binding
If i have a Controller Action that may recieve both HTTP GET and HTTP POST from a number of different sources with each source sending different data eg 如果我有一个Controller Action,它可以从多个不同的源接收HTTP GET和HTTP POST,而每个源都发送不同的数据,例如
Is it possible to have a controller action that will cater for all these cases and perform binding automatically eg public ActionResult Test(Dictionary data) { // Do work ... return View(); 是否有可能会满足所有这些情况并自动执行绑定的控制器动作,例如public ActionResult Test(Dictionary data){//做... return View(); }
}
Is this possible with a custom binder or some other way? 使用自定义活页夹或其他方法可以做到吗? Dont want to work directly with HttpContext.Request if possible
如果可能,不要直接使用HttpContext.Request
The usual pattern is to have two controller methods One controller method handles the GET, the other controller method handles the POST: 通常的模式是有两个控制器方法,一个控制器方法处理GET,另一个控制器方法处理POST:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult MyControllerMethod(string itemX, string itemY)
{
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult MyControllerMethod(MyViewDataObject data)
{
}
If you need help binding lists, collections or dictionaries you can find it here . 如果您需要帮助绑定列表,集合或词典,可以在此处找到。
This solution works, not best for unit testing 此解决方案有效,并非最适合单元测试
public object BindModel(
ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
TestIBE.Models.IBERequest _IBERequest;
HttpContextBase _httpContext;
Dictionary<string, string> _requestData;
_httpContext = controllerContext.HttpContext;
_requestData = this.CreateRequestData(_httpContext.Request);
_IBERequest = new TestIBE.Models.IBERequest(
_httpContext.Session.SessionID,
_httpContext.Request.UserHostAddress,
_httpContext.Request.UserAgent,
_httpContext.Request.Url,
_requestData);
return _IBERequest;
}
private Dictionary<string, string> CreateRequestData(
HttpRequestBase subject)
{
Dictionary<string, string> _result;
_result = new Dictionary<string, string>();
subject.Form.AllKeys.ForEach(key => _result.Add(key, subject.Form[key]));
subject.QueryString.AllKeys.ForEach(key => { if (!_result.ContainsKey(key)) { _result.Add(key, subject.QueryString[key]); } });
return _result;
}
public class IBEController : Controller
{
public ActionResult Landing(
[ModelBinder(typeof(TestIBE.Helpers.Binders.IBEModelBinder))] TestIBE.Models.IBERequest IBERequest)
{
// TODO
return View();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.