Modification of ajax js for ajax Asp. Net mvc

Many beginning C # ASP.NET MVC programmers (hereinafter mvc) are faced with the task of sending data using Ajax. That's only in practice, this task is not so easy.
 
 
At my work I try to follow certain principles of software development. One of them is the minimization of code writing and the creation of universal classes and functions. It is this principle that assumed the use of jquery.unobtrusive-ajax.js and class Ajax for mvc .
 
stackoverflow on each solution offered the same thing. Do not use Ajax.BeginForm, use FormData, make a php handler, and more cloud tips to increase the code.
 
 
As I said earlier, in my products I stick to the principles and once the answer that would satisfy my requirements, was not found, I had to do everything myself.
 
 
The first thing that was required was to determine which function was in jquery.unobtrusive-ajax.js is responsible for the formation of data.
 
 
$ (document) .on ("submit", "form[data-ajax=true]", function (evt) {
var clickInfo = $ (this) .data (data_click) ||[],
clickTarget = $ (this). data (data_target),
isCancel = clickTarget && (clickTarget.hasClass ("cancel") || clickTarget.attr ('formnovalidate')! == undefined);
.evt.preventDefault ();
if (! isCancel &&! validate (this)) {
return;
}
asyncRequest (this, {
url: this.action,
type: this.method || "GET",
//What about us interested in
dаta: clickInfo.concat ($ (this) .serializeArray ())
});
});

 
We are interested in the function $ (this) .serializeArray () . In the variable $ (this) our form
comes. and then becomes an array. Having tested it in the console, as well as its analogue serialize () it was determined that these functions do not download files in principle. Hence the decision to rewrite it.
 
 
But first you need to solve the problem with downloading the file, for this we will use the class FileReader .
 
 
$ (document) .on ("change", "form[data-ajax=true]input[type=file]", function (evt) {
var form = $ ($ (evt.target) .parents ("form")[0]);
.if (evt.target.files.length> 0) {
var fileObj = evt.target.files[0];
var reader = new FileReader ();
.read.onload = function () {
.evt .target.setAttribute ("data-ajax-image-data", reader.result);
form.find ("button[type=submit]")[0].classList.remove ("disabled");
}
.reader .onerror = function () {
.console.log ("Error while loading");
form.find ("button[type=submit]")[0].classList.remove ("disabled");
}
.form .find ("button[type=submit]")[0].classList.add ("disabled");
.read.readAsDataURL (fileObj);
}
});

 
A little bit about the code.
 
 
First, we bind the event to the input change, the choice is "change".
 
 
Then we check if the file is selected.
 
 
If the file is selected, we start downloading it. The problem was that the data should be stored somewhere, in the example we will write the data into the attribute of the object itself.
 
 
We block the confirmation button until the file is downloaded.
 
 
In case of error, write this to the console. This is not the final version of the function, everyone can upgrade it to their own needs.
 
 
After we created the download of the file data, we proceed to the serialization upgrade.
 
 
function selfFormSerializeArray (form) {
var array = form.serializeArray ();
for (var i = 0; i
 
And we use this function in the main function.
 
 
$ (document) .on ("submit", "form[data-ajax=true]", function (evt) {
var clickInfo = $ (this) .data (data_click) ||[],
clickTarget = $ (this). data (data_target),
isCancel = clickTarget && (clickTarget.hasClass ("cancel") || clickTarget.attr ('formnovalidate')! == undefined);
.evt.preventDefault ();
if (! isCancel &&! validate (this)) {
return;
}
asyncRequest (this, {
.url: this.action,
type: this.method || "GET",
dаta: clickInfo.concat (selfFormSerializeArray ($ (this))) //clickInfo.concat ($ (this) .serializeArray ())
});
});

 
Upon completion, you need to append the handler and the data parser. In a hurry, it looks something like this.
 
 
The handler is
 
 
public PartialViewResult UploadAvatarImage ()
{
if (! ImageHelper.LoadAvatarImage (this.Request.Form["avatarFile"]))
{
return null;
}
return PartialView ("Null");
}

 
Helper
 
 
public static bool LoadAvatarImage (string data)
{
try
{
var file = AjaxFile.Create (data);
return true;
}
catch (Exception ex)
{
return false;
}

 
Parser
 
 
public AjaxFile (string data)
{
var infos = data.Split (',');
this.Type = infos[0].Split (';')[0].Split (':')[1].Split ('/')[1];
this.Source = Convert.FromBase64String (infos[1]); ;
}
public static AjaxFile Create (string data)
{
return new AjaxFile (data);
}

 
Congratulations! Now you can upload files using the standard Ajax for mvc.
C# / Ajax
+ 0 -

Add comment