When jquery. unobtrusive-ajax.js meets the Web API, jqueryajaxapi

Source: Internet
Author: User

When jquery. unobtrusive-ajax.js meets the Web API, jqueryajaxapi

Recently, I am familiar with the Abp framework, which is based on the DDD domain-driven design... In the previous section, you can bypass mvc and directly call the webapi dynamically generated based on the app layer. This is amazing ~, Web APIs have been exposed before. The lightweight version of WCF is generally used as a write and development service interface. The form is similar to that of MVC, I just don't want to render the view (Other restful-based designs do not need to be pulled ).

Therefore, my idea is to use mvc view for model verification on the page and use jquery to submit operations. the unobtrusive-ajax.js automatically collects form Content to directly call webapi; because few people do not much, view model is dto, so with jquery. validate. unobtrusive. javaScript code is as follows:

@ Model ArticleEdit @ section styles {<link href = "~ /Content/bootstrap-tagsinput.css "rel =" stylesheet "/>}< form class =" form-horizontal "action ="/api/services/app/article/CreateAndGetIdAsync "method =" post "novalidate =" novalidate "data-ajax =" true "data-ajax-success =" AjaxCallback "data-ajax-method =" Post "role =" form "> <div class = "form-group"> @ Html. labelFor (o => o. title, new {@ class = "col-sm-2 control-label"}) <div class = "col-sm-10"> @ Html. textBoxFor (o => o. title, new {@ class = "form-control"}) @ Html. validationMessageFor (o => o. title) </div> <div class = "hr-line-dashed"> </div> <div class = "form-group"> @ Html. labelFor (o => o. keywords, new {@ class = "col-sm-2 control-label"}) <div class = "col-sm-10"> @ Html. textBoxFor (o => o. keywords, new {@ class = "form-control", data_role = "tagsinput", placeholder = "Tab key or ', 'segmentation"}) @ Html. validationMessageFor (o => o. keywords) </div> <div class = "form-group"> @ Html. labelFor (o => o. description, new {@ class = "col-sm-2 control-label"}) <div class = "col-sm-10"> @ Html. textBoxFor (o => o. description, new {@ class = "form-control"}) @ Html. validationMessageFor (o => o. description) </div> <div class = "form-group"> @ Html. labelFor (o => o. content, new {@ class = "col-sm-2 control-label"}) <div class = "col-sm-10"> @ Html. textAreaFor (o => o. content, new {style = "height: 300px;"}) @ Html. validationMessageFor (o => o. content) </div> <div class = "hr-line-dashed"> </div> <div class = "form-group"> <div class = "col-sm-4 col-sm-offset-2 "> <button class =" btn-primary "type =" submit "> Save content </button> <button class =" btn-white "type =" reset"> Reset </button> </div> </form> @ section scripts {
// Jquery. js & bootstrap. js here <script src = "~ /Scripts/jquery. unobtrusive-ajax.js "> </script> <script src = "~ /Scripts/jquery. validate. unobtrusive. js "> </script> <script src = "~ /Scripts/bootstrap-tagsinput.js "> </script> <script type =" text/javascript "> function AjaxCallback (data) {console. log ("new data id:" + data. result) ;}</script>}

ArticleEdit:

[AutoMap (typeof (Article)] public class ArticleEdit {[Display (Name = "Article title")] [Required (ErrorMessage = "{0} cannot be blank")] [MaxLength (Article. maxTitleLength, ErrorMessage = "{0} cannot exceed {1} characters")] public string Title {get; set ;} /// <summary> /// keyword /// </summary> [Display (Name = "keyword")] [StringLength (Article. maxKeywordsLength, ErrorMessage = "{0} cannot exceed {1} characters")] public string Keywords {get; set ;} /// <summary> /// description /// </summary> [Display (Name = "Description")] [StringLength (Article. maxDescriptionLength, ErrorMessage = "{0} cannot exceed {1} characters")] public string Description {get; set ;} /// <summary> /// body content /// </summary> [Display (Name = "body content")] [DataType (DataType. multilineText)] [AllowHtml] public string Content {get; set ;}}
View Code

Corresponding interfaces of the application layer of Abp:

Task <int> CreateAndGetIdAsync (ArticleEdit input); // a post api is generated here.

This is all done ......

//////////////////////////////////////// //////////////////////////////////////// //// // I am a gorgeous splitting line /////////// //////////////////////////////////////// //////////////////////////////////////// ///////////////////////

That's strange.

Solution:

The application layer cannot receive data. After repeated tests: it is normal to call the mvc post action, indicating that the view content is correct. Replace ArticleEdit with string and other simple types, according to the dynamic api instructions on the ABC official website, the WebApi test tool Swagger was installed to call this api. This made me more confused. Is it because the datatype submitted by ajax is incorrect, then try to test with jquery ajax: $. post ("http: // *****/CreateAndGetIdAsync", {Title: "", Keywords: "", Discription: "", Content: ""}, function () {console. log ("new data id:" + data. result) ;}); failed. **************** Finally, the correct parameter passing format is found as follows:

$. Ajax ({type: "method", url: "http: // *****/CreateAndGetIdAsync", data: '{Title: "", Keywords: "", Discription: "", Content: ""} ', // note the character string dataType: "json", contentType: "application/json", // $. post () cannot be used because success: function (response) {console. log ("new data id:" + data. result );}});

The problem was found again by webapi pitfall, and its ModelBinder is not as powerful as MVC (detailed https://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api ), the ModelBinder of mvc can search for models of complex data types bound to data from the url and post body at the same time, as for Microsoft, there is nothing to make them the same, or because webapi is based on restful design ¥ @... &.

Solution: Replace the default webapi ModelBinder with the default one. I believe that it can be done by directly copying the mvc ModelBinder and registering it with it. At the moment, I do not want to use this method to undermine its style, my soft design certainly has his own principles; the other one I use is to change jquery. the source code of the unobtrusive-ajax.js determines webapi requests, but fortunately the file code is few (this is not an elegant way), the change is as follows:

1. in jquery. jquery was introduced before unobtrusive-ajax.js. serialize-object.js (a plug-in for automatic serialization of forms, you can also refer to here to write, jquery serializeArray () format is not correct; this plug-in is not very compatible with the asp.net mvc model in the array Generation input name naming method ).

2. Locate the ajax request from jquery. unobtrusive-ajax.js $. ajax (options); changed:

If (method = "POST" & element. getAttribute ("data-ajax-webapi") {options. contentType = "application/json; charset = UTF-8"; options. data = $ (element ). serializeJSON ();} // This sentence is added $. ajax (options );

3. Add data-ajax-webapi = "true" to the form in the first code ".

Summary:

1. The Design of webapi is quite different from that of mvc, including many other places.

2. The webapi should support the json parameter transfer of $. post ~~~~

3. Learn angularjs if you have time.

4. Endless life

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.