Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Sample Analysis of submitted Array when ASP.NET MVC encounters jQuery.Ajax

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is to share with you about the example analysis when ASP.NET MVC encounters jQuery.Ajax to submit an array. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.

When ASP.NET MVC submits the array through JQuery's Ajax, MVC's model binder mechanism fails. We have to write custom code in Controller to convert the data submitted by Request into the required data type. The process is often tedious. The following is a practical example of a project to demonstrate how to solve this problem and provide a general solution.

Requirement description

When the user changes the configuration, the Ajax needs to be submitted to the server.

Front-end code:

Var items = []; $("input:checked") .each (function () {items.push ($(this). Val ();}); $.ajax ({type: 'post', url:' Configure/Status', data: {answers: items})

Backend code:

Public enum AnswerStatus {Correct = 1, Incorrect = 2, Unanswered = 3} [HttpPost] public ActionResult Status (IList answers) {… . }

The answers here is always null. The artifact fiddler came out and found that the data submitted by Array with JQuery.Ajax was always submitted with a "[]" after the name. That's where the problem lies.

Modify the code based on the results found:

[HttpPost] public ActionResult Status (IList answers) {answers = Request.Form.GetValues ("answers []") .Select (d = > d.ToEnum (AnswerStatus.Unanswered). ToList ();}

Although this can solve my problem, I have to parse the request manually every time I submit an Array, depending on going back to the Stone Age overnight. In fact, we will immediately think of MVC's Mode Binder.

Attempt to perform * refactoring:

Public class AnswerModelBinder: IModelBinder {public override object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) {return controllerContext.RequestContext.HttpContext.Request.Form.GetValues ("answers []") .Select (d = > d.ToEnum (AnswerStatus.Unanswered). ToList ();}}

The taste of hard coding is too strong, another type has to be rewritten, and the workload is more than before, but Controller has become elegant. This practice of wasting youth and consuming electricity still does not meet the requirements.

Refactoring for the second time: DefaultModelBinder appearance

The DefaultModelBinder of * can be bound to any type. Unfortunately, the name passed by client is appended with "[]", which makes it impossible for DefaultModelBinder to parse accurately. So can we deceive DefaultModelBInder?

Looking at ModelBindingContext, we find that there is a ModelName attribute, which feels a bit like the name of the parameter to be bound. Debugging trace finds that ModelName is indeed the name of the parameter. If we modify ModelName to make it consistent with the name passed by client, we will be able to make full use of DefaultModelBinder. So start to create a JQAjaxModelBinder.

And inherits from DefaultModelBinder:

Public override object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext) {if (bindingContext.ModelType.IsEnumerable ()) {var key = bindingContext.ModelName + "[]"; var valueResult = bindingContext.ValueProvider.GetValue (key); if (valueResult! = null & &! string.IsNullOrEmpty (valueResult.AttemptedValue)) {bindingContext.ModelName = key;} return base.BindModel (controllerContext, bindingContext) } / / how to use custom ModelBinder. The method is Action public ActionResult Status ([ModelBinder (typeof (ModelBinder.JQAjaxModelBinder))] IList answers) {… }

At this time, the Status (Action) method in Controller can correctly get the data from the front end. And it's strongly typed. Of course, many programmers are lazy, and the author is one of them. The author doesn't even want to write the parameter in front of Parameter ([ModelBinder (typeof (ModelBinder.JQAjaxModelBinder))]), so let's register it directly in ModelBinders. In fact, there is also some trouble when registering. I must set Type. I can know those types in advance. Simply set JQAjaxModelBinder to the default ModerBinder, once and for all, no more worries.

Different registration methods for ModelBinder

This is the approach used above by adding a ModelBinder tag to the parameters of the Action method.

Add a ModelBinder tag to the data type

[ModelBinder (typeof (ModelBinder.JQAjaxModelBinder))] Public class User {}

Register through ModelBinders

ModelBinders.Binders.Add (typeof (User), new ModelBinder.JQAjaxModelBinder ())

Set the default ModerBinder

ModelBinders.Binders.DefaultBinder = new ModelBinder.JQAjaxModelBinder ()

Postscript: when we are in development, we often do repetitive things, when a thing is repeated many times, we need to stop and think carefully, can we abstract these things out and make a general solution? Solve these problems once and for all.

The above is the example analysis when ASP.NET MVC encounters jQuery.Ajax to submit an array. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report