📜 ⬆️ ⬇️

AJAX Integration in ASP.NET MVC 4

Probably, there is no longer a web developer who has not heard of Ajax. Microsoft in this situation can not stay away, with each release trying to make life easier for us, ASP.NET MVC developers. But before I continue the article, I digress a little from the topic.

When I met the MVC framework, it was then only in the second version and, faced with such helpers as @Ajax.... , frankly, their implementation on the client side did not impress me. No, no, I thought to myself, I have jQuery with my $.ajax , for my eyes. So I forgot about them for several years, to my great regret having missed the moment with the third release. That was, that was. Fortunately, I took the mind and read two books on MVC 4. Next, I’ll tell you how you can shorten the writing of lines of code thanks to the helpers I mentioned above.

To begin with, MVC can work with two variants of Ajax libraries (of course, I mean from the box, nothing more) - jQuery and Microsoft Ajax. To know for which adapter to create markup, there is a setting in the web.config UnobtrusiveJavaScriptEnabled and the corresponding value true (for working with jQuery) and f alse (for working with Microsoft Ajax). If we need to change the value for only one view, we can use the method - @{Html.EnableUnobtrusiveJavaScript(bool);} . I want to note that this setting affects the formation of validation data on the client side.
')

Depending on what option you prefer, you need to connect the appropriate adapter. For Microsoft Ajax

 <script src="~/Scripts/MicrosoftAjax.js" type="text/javascript"></script> <script src="~/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script> 

, a for jQuery

 <script src="~/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script> 

As I wrote above, the jQuery version suits me perfectly. Therefore, I will follow the path of unobtrusive JavaScript (i.e. web.config with /> ), and start with the simplest.

ActionLink


Consider this task. There is a reference when we click on which we want to update the contents of the container. What I did before.

Slice of action method

 public ActionResult Index() { if (Request.IsAjaxRequest()) return PartialView("_IndexPartial"); return View(); } 

Index presentation

 <script type="text/javascript"> jQuery(function($) { $('#update-container').click(function(e) { e.preventDefault(); $.ajax({ url: '@Url.Action("Index", "Home")', success: function(data) { $('#container').html(data); } }); }) }) </script> <div id="container"> @Html.Partial("_IndexPartial") </div> @Html.ActionLink(" ", "Index", "Home", new {}, new {id = "update-container"}) 

_IndexPartial partial view

 <div>     </div> 

Most familiar with a helper method like Html. ActionLink(...) Html. ActionLink(...) presented above. It would seem that there are not many lines of code in principle, and I’m used to programming this way, so everything is in order, but I’m a very lazy programmer and am fighting for cleanliness and code reduction to the best of my ability. Therefore, I would be pleased to reduce the presentation from 22 lines to 5. And Ajax.ActionLink(...) comes to my Ajax.ActionLink(...) (of course, skeptics may say that instead of $.ajax you could use .load or $.get , but essentially it does not change, we have reduced the idea, which sometimes begins to swell with us)

Voila, Index presentation

 <div id="container"> @Html.Partial("_IndexPartial") </div> @Ajax.ActionLink(" ", "Index", "Home", new {}, new AjaxOptions{UpdateTargetId = "container"}, new {id = "update-container"}) //id     ,     

The difference between the two extended methods Html.ActionLink and Ajax.ActionLink consists of only one parameter, the AjaxOptions object. Let's talk about it and talk.

AjaxOptions




As you can see, there are not many properties in principle; on the other hand, this is good when they start to create a silver bullet, be it an object or a library, it simply becomes not likely cumbersome and inoperable.

Which of the properties for what is responsible, I can not say better MSDN.



Let's go over the properties:

Confirm is an analogue of javascript confirm(...)

HttpMethod is of the string type, the most interesting thing is that MS forced it to be limited to only 2 methods, I wondered why, and apparently the algorithm is such that everything is not GET , null or an empty string after .Trim() is all POST

InsertionMode - an enumeration with the values ​​" InsertAfter " (insert at the end of the container), " InsertBefore " (insert at the beginning of the container) or " Replace " (replace the contents of the container)

Loading... - initial hidden item

On..... - javascript functions, by analogy with $.ajax

Url - a link to a separate address of the ajax request, if we need to separate the request from the ajax request to different routes / controllers / actions / parameters (underline)

Ajax helper methods


In the end, I would like to give a sign of methods that will facilitate our lives from time to time.
Ajax.ActionLinkCreates a hyperlink to a controller action that, when clicked, sends an Ajax request.
Ajax.RouteLinkLooks like Ajax.ActionLink , but creates a link to a specific route, not a controller action.
Ajax.BeginFormCreates a form element that will send input to a specific controller action.
Ajax.BeginRouteFormLooks like Ajax.BeginForm , but sends a request for a particular route, and not to the controller action
Ajax.GlobalizationScriptCreates a link to the globalization script, which contains information about the language and regional settings
Ajax.JavaScriptStringEncodeEncodes the string for safe use in javascript

Ensuring gradual deterioration


Consider this situation. Ajax request returns JSON / XML / Partial representation - and everything is fine, but this approach is not at all acceptable if the user has disabled JavaScript, or the browser does not support it at all. In such cases, you must fully return the page to the user. One solution is to use “wiring” in one action method with determining whether this request is an Ajax request. This can be done using Request.IsAjaxRequest() , as discussed above.

The second solution to the problem is to create two different methods of action: one for the Ajax request, and the second for the usual one. Let's look at this option in more detail, on the simplified task of saving the comment received from the user.

Create two action methods

 [HttpPost] public ActionResult AddComment(string comment) { //  return View(); } [HttpPost] public ActionResult AddCommentAjax(string comment) { //  return Json(new {resultMessage = "   !"}); } 

AddComment

 <h3>   !</h3> 

and our form submission

 <script type="text/javascript"> function OnSuccessComment(data) { alert(data.resultMessage); } </script> @using (Ajax.BeginForm("AddComment", new AjaxOptions { Url = Url.Action("AddCommentAjax"), OnSuccess = "OnSuccessComment", HttpMethod = "POST" })) { @Html.TextArea("comment") <input type="submit" value=" "/> } 

How it works

The following form is rendered for the browser.

 <form id="comment-form" action="/Home/AddComment" method="POST" data-ajax-url="/Home/AddCommentAjax" data-ajax-success="OnSuccessComment" data-ajax-method="POST" data-ajax="true"> <textarea rows="2" name="comment" id="comment" cols="20"></textarea> <input type="submit" value=" "> </form> 

We see that the difference from @using (Html.BeginForm("AddComment", "Home")) is only in additional data- attributes. In other words, for disabled Javascript, the form will be public ActionResult AddComment(string comment) to the public ActionResult AddComment(string comment) . When JavaScript is enabled, the adapter reads data from the data- attributes, intercepts the form submission, and makes a request for a public ActionResult AddCommentAjax(string comment) . We get the successful result in the form of the transmitted JSON and process the OnSuccessComment function in the specified js.

Summary


The purpose of my article was only to show that some things can be accelerated a little and not reinvent the wheel (I judge it only by myself).



The following chapters of books led me to writing this article:
Ajax in ASP.NET MVC (ASP.NET MVC 4 in action)
and
Helper methods for URL and Ajax (pro ASP.NET MVC 4)




Source: https://habr.com/ru/post/180011/


All Articles