How to do a ASP.NET MVC Ajax form post with multipart/form-data? - asp.net

I am working on a ASP.NET MVC web site which has a form that allows for the upload of files using the multipart/form data enctype option on the form tag like so
<form enctype="multipart/form-data" method="post" action='<%= Url.Action("Post","Entries",new {id=ViewData.Model.MemberDetermination.DeterminationMemberID}) %>'>
How would I write this to do an ASP.NET MVC Ajax form post instead?

It is possible but it's a long way.
Step 1: write your form
ex:
#using (Ajax.BeginForm(YourMethod, YourController, new { id= Model.Id }, new AjaxOptions {//needed options }, new { enctype = "multipart/form-data" }))
{
<input type="file" id="image" name="image" />
<input type="submit" value="Modify" />
}
Step 2: intercept the request and send it to the server
<script type="text/javascript">
$(function() {
$("#form0").submit(function(event) {
var dataString;
event.preventDefault();
var action = $("#form0").attr("action");
if ($("#form0").attr("enctype") == "multipart/form-data") {
//this only works in some browsers.
//purpose? to submit files over ajax. because screw iframes.
//also, we need to call .get(0) on the jQuery element to turn it into a regular DOM element so that FormData can use it.
dataString = new FormData($("#form0").get(0));
contentType = false;
processData = false;
} else {
// regular form, do your own thing if you need it
}
$.ajax({
type: "POST",
url: action,
data: dataString,
dataType: "json", //change to your own, else read my note above on enabling the JsonValueProviderFactory in MVC
contentType: contentType,
processData: processData,
success: function(data) {
//BTW, data is one of the worst names you can make for a variable
//handleSuccessFunctionHERE(data);
},
error: function(jqXHR, textStatus, errorThrown) {
//do your own thing
alert("fail");
}
});
}); //end .submit()
});
</script>
Step 3: Because you make an ajax call you probably want to replace some image or something of multipart/form-data
ex:
handleSuccessFunctionHERE(data)
{
$.ajax({
type: "GET",
url: "/Profile/GetImageModified",
data: {},
dataType: "text",
success: function (MSG) {
$("#imageUploaded").attr("src", "data:image/gif;base64,"+msg);
},
error: function (msg) {
alert(msg);
}
});
}
The MSG variable is an base64 encrypted string. In my case it's the source of the image.
In this way I managed to change a profile picture and after that the picture is immediately updated.
Also make sure you add in Application_Start (global.asax)
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
Pretty nice no?
P.S.: This Solution works so don't hesitate to ask more details.

I came across this little hack, which resolves it nicely
window.addEventListener("submit", function (e) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if (form.dataset.ajaxUpdate) {
var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
if (updateTarget) {
updateTarget.innerHTML = xhr.responseText;
}
}
}
};
xhr.send(new FormData(form));
}
}
}, true);

You can use some additional uploaders (e.g. jQuery multiple file uploader) (I prefer this way and I prefer not to use MS Ajax)
Use:
AjaxHelper.BeginForm("Post", "Entries", new {id=ViewData.Model.MemberDetermination.DeterminationMemberID}, new AjaxOptions(){/*some options*/}, new {enctype="multipart/form-data"})
But in second case I'm not sure that it will work.

The jquery forms plugin supports file uploads in this way.

Code which I used and it works !! It's a copy of #James 'Fluffy' Burton solution. I just improvising his answer so that people who is new to MVC will be able to quickly understand the consequences.
Following are my View:
#using (Ajax.BeginForm("FileUploader", null, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "AjaxUpdatePanel" }, new { enctype = "multipart/form-data", id = "frmUploader" })){
<div id="AjaxUpdatePanel">
<div class="form-group">
<input type="file" id="dataFile" name="upload" />
</div>
<div class="form-group">
<input type="submit" value="Upload" class="btn btn-default" id="btnUpload"/>
</div>
</div>}
<script>
window.addEventListener("submit", function (e) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
if (form.dataset.ajaxUpdate) {
var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
if (updateTarget) {
updateTarget.innerHTML = xhr.responseText;
}
}
}
};
xhr.send(new FormData(form));
}
}
}, true);
Following are my controller:
[HttpPost]
public JsonResult FileUploader(HttpPostedFileBase upload)
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
if (upload.FileName.EndsWith(".csv"))
{
Stream stream = upload.InputStream;
DataTable csvTable = new DataTable();
using (CsvReader csvReader = new CsvReader(new StreamReader(stream), true))
{
csvTable.Load(csvReader);
}
}
else
{
return Json(new { dataerror = true, errormsg = "This file format is not supported" });
}
}
else
{
return Json(new { dataerror = true, errormsg = "Please Upload Your file" });
}
}
return Json(new { result = true });
}
Following is the quick Note of above code:
Through Ajax, I have posted my excel (*.csv) file to Server and read it to an DataTable using a Nuget package (LumenWorksCsvReader).
Hurray! It works. Thanks #James

I actually answered the question myself...
<% using (Ajax.BeginForm("Post", "Entries", new { id = ViewData.Model.MemberDetermination.DeterminationMemberID }, new AjaxOptions { UpdateTargetId = "dc_goal_placeholder" }, new { enctype = "multipart/form-data" }))

For those who still have problems using #Ajax.BeginForm for multipart enctypes / file uploads in MVC
Diagnosis and proposed solution
Running the “Inspect element” tool on a form element generated by the #Ajax.BeginForm helper reveals that the helper, rather inexplicably, overrides the controller parameter specified. This is the case if you implemented a separate controller for your partial postback.
A quick-fix for the problem is to explicitly specify your html action attribute value as /<yourcontrollername>/<youractionname>.
Example
#using (Ajax.BeginForm("", "", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "<TargetElementId>", InsertionMode = InsertionMode.Replace }, new { enctype = "multipart/form-data", action = "/<Controller>/<Action>" }))

If you need to use the OnSuccess AjaxOption and/or use Request.IsAjaxRequest() in the controller to check the request type i.e.
#using (Ajax.BeginForm("FileUploader", null, new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "elementToUpdate", OnSuccess = "mySuccessFuntion(returnedData)", OnFailure = "myFailureFuntion(returnedData)"}, new { enctype = "multipart/form-data" }))
Then you can use the following code (I've modified #James 'Fluffy' Burton's answer). This will also convert the response text to JSON object if it can (you can omit this if you want).
<script>
if(typeof window.FormData === 'undefined') {
alert("This browser doesn't support HTML5 file uploads!");
}
window.addEventListener("submit", function (e) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action);
xhr.setRequestHeader("x-Requested-With", "XMLHttpRequest"); // this allows 'Request.IsAjaxRequest()' to work in the controller code
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
var returnedData; //this variable needs to be named the same as the parameter in the function call specified for the AjaxOptions.OnSuccess
try {
returnedData = JSON.parse(xhr.responseText); //I also want my returned data to be parsed if it is a JSON object
}catch(e){
returnedData = xhr.responseText;
}
if (form.dataset.ajaxSuccess) {
eval(form.dataset.ajaxSuccess); //converts function text to real function and executes (not very safe though)
}
else if (form.dataset.ajaxFailure) {
eval(form.dataset.ajaxFailure);
}
if (form.dataset.ajaxUpdate) {
var updateTarget = document.querySelector(form.dataset.ajaxUpdate);
if (updateTarget) {
updateTarget.innerHTML = data;
}
}
}
};
xhr.send(new FormData(form));
}
}
}, true);
</script>
N.B. I use the javascript function eval() to convert the string in to a function... if anyone has a better solution please comment.
I also use JQuery JSON.parse() so this isn't a vanilla javascript solution but it isn't required for the script to function so it could be removed.

I mixed Brad Larson answer with Amirhossein Mehrvarzi, because Brad answer wasn't providing any way to handle the response and Amirhossein was causing 2 postbacks.
I just added ($('#formBacklink').valid()) to call model validation before send.
window.addEventListener("submit", function (e) {
if ($('#formBacklink').valid()) {
var form = e.target;
if (form.getAttribute("enctype") === "multipart/form-data") {
if (form.dataset.ajax) {
e.preventDefault();
e.stopImmediatePropagation();
var dataString;
event.preventDefault();
var action = $("#formBacklink").attr("action");
if ($("#formBacklink").attr("enctype") == "multipart/form-data") {
//this only works in some browsers.
//purpose? to submit files over ajax. because screw iframes.
//also, we need to call .get(0) on the jQuery element to turn it into a regular DOM element so that FormData can use it.
dataString = new FormData($("#formBacklink").get(0));
contentType = false;
processData = false;
} else {
// regular form, do your own thing if you need it
}
$.ajax({
type: "POST",
url: action,
data: dataString,
dataType: "json", //change to your own, else read my note above on enabling the JsonValueProviderFactory in MVC
contentType: contentType,
processData: processData,
success: function (data) {
//BTW, data is one of the worst names you can make for a variable
//handleSuccessFunctionHERE(data);
},
error: function (jqXHR, textStatus, errorThrown) {
//do your own thing
}
});
}
}
}
}, true);

Ajax.BegineForm() works with multipart form data and here's the working code example for the same:
View:
#using(Ajax.BeginForm("UploadFile","MyPOC",
new AjaxOptions {
HttpMethod = "POST"
},
new
{
enctype = "multipart/form-data"
}))
{
<input type="file" name="files" id="fileUploaderControl" />
<input type="submit" value="Upload" id="btnFileUpload" />
}
Controller Action Method:
public void UploadFile(IEnumerable<HttpPostedFileBase> files)
{
HttpPostedFileBase file = files.FirstOrDefault(); //Attach a debugger here and check whether you are getting your file on server side or null.
if (file != null && file.ContentLength > 0)
{
//Do other validations before saving the file
//Save File
file.SaveAs(path);
}
}
P.S. Make sure the "name" attribute of the file uploader control and the name of the parameter passed to Action method UploadFile() has to be same (i.e. "files" in this case).

From my little investigation. All the answers above seems to be correct depending on the problem one is having with the Ajax.BeginForm. However, I have just observe that the problem is with the ~/Scripts/jquery.unobtrusive-ajax.min.js javascript library in some case. So in my case I just removed it from the view model and sort of decided to use JQuery Form plugin for my required need along with the HTML Form instead. This has been suggested above.

You can use this code instead of eval
var body = "function(a){ " + form.dataset.ajaxSuccess + "(a) }";
var wrap = s => "{ return " + body + " };"
var func = new Function(wrap(body));
func.call(null).call(null, returnedData);

Related

How should I encode a form value I send with XMLHttpRequest [duplicate]

I'd like to send some data using an XMLHttpRequest in JavaScript.
Say I have the following form in HTML:
<form name="inputform" action="somewhere" method="post">
<input type="hidden" value="person" name="user">
<input type="hidden" value="password" name="pwd">
<input type="hidden" value="place" name="organization">
<input type="hidden" value="key" name="requiredkey">
</form>
How can I write the equivalent using an XMLHttpRequest in JavaScript?
The code below demonstrates on how to do this.
var http = new XMLHttpRequest();
var url = 'get_data.php';
var params = 'orem=ipsum&name=binny';
http.open('POST', url, true);
//Send the proper header information along with the request
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
In case you have/create an object you can turn it into params using the following code, i.e:
var params = new Object();
params.myparam1 = myval1;
params.myparam2 = myval2;
// Turn the data object into an array of URL-encoded key/value pairs.
let urlEncodedData = "", urlEncodedDataPairs = [], name;
for( name in params ) {
urlEncodedDataPairs.push(encodeURIComponent(name)+'='+encodeURIComponent(params[name]));
}
var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
xhr.send('user=person&pwd=password&organization=place&requiredkey=key');
Or if you can count on browser support you could use FormData:
var data = new FormData();
data.append('user', 'person');
data.append('pwd', 'password');
data.append('organization', 'place');
data.append('requiredkey', 'key');
var xhr = new XMLHttpRequest();
xhr.open('POST', 'somewhere', true);
xhr.onload = function () {
// do something to response
console.log(this.responseText);
};
xhr.send(data);
Use modern JavaScript!
I'd suggest looking into fetch. It is the ES5 equivalent and uses Promises. It is much more readable and easily customizable.
const url = "http://example.com";
fetch(url, {
method : "POST",
body: new FormData(document.getElementById("inputform")),
// -- or --
// body : JSON.stringify({
// user : document.getElementById('user').value,
// ...
// })
}).then(
response => response.text() // .json(), etc.
// same as function(response) {return response.text();}
).then(
html => console.log(html)
);
In Node.js, you'll need to import fetch using:
const fetch = require("node-fetch");
If you want to use it synchronously (doesn't work in top scope):
const json = await fetch(url, optionalOptions)
.then(response => response.json()) // .text(), etc.
.catch((e) => {});
More Info:
Mozilla Documentation
Can I Use (96% Nov 2020)
David Walsh Tutorial
Here is a complete solution with application-json:
// Input values will be grabbed by ID
<input id="loginEmail" type="text" name="email" placeholder="Email">
<input id="loginPassword" type="password" name="password" placeholder="Password">
// return stops normal action and runs login()
<button onclick="return login()">Submit</button>
<script>
function login() {
// Form fields, see IDs above
const params = {
email: document.querySelector('#loginEmail').value,
password: document.querySelector('#loginPassword').value
}
const http = new XMLHttpRequest()
http.open('POST', '/login')
http.setRequestHeader('Content-type', 'application/json')
http.send(JSON.stringify(params)) // Make sure to stringify
http.onload = function() {
// Do whatever with response
alert(http.responseText)
}
}
</script>
Ensure that your Backend API can parse JSON.
For example, in Express JS:
import bodyParser from 'body-parser'
app.use(bodyParser.json())
Minimal use of FormData to submit an AJAX request
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"use strict";
function submitForm(oFormElement)
{
var xhr = new XMLHttpRequest();
xhr.onload = function(){ alert (xhr.responseText); } // success case
xhr.onerror = function(){ alert (xhr.responseText); } // failure case
xhr.open (oFormElement.method, oFormElement.action, true);
xhr.send (new FormData (oFormElement));
return false;
}
</script>
</head>
<body>
<form method="post" action="somewhere" onsubmit="return submitForm(this);">
<input type="hidden" value="person" name="user" />
<input type="hidden" value="password" name="pwd" />
<input type="hidden" value="place" name="organization" />
<input type="hidden" value="key" name="requiredkey" />
<input type="submit" value="post request"/>
</form>
</body>
</html>
Remarks
This does not fully answer the OP question because it requires the user to click in order to submit the request. But this may be useful to people searching for this kind of simple solution.
This example is very simple and does not support the GET method. If you are interesting by more sophisticated examples, please have a look at the excellent MDN documentation. See also similar answer about XMLHttpRequest to Post HTML Form.
Limitation of this solution: As pointed out by Justin Blank and Thomas Munk (see their comments), FormData is not supported by IE9 and lower, and default browser on Android 2.3.
NO PLUGINS NEEDED!
Select the below code and drag that into in BOOKMARK BAR (if you don't see it, enable from Browser Settings), then EDIT that link :
javascript:var my_params = prompt("Enter your parameters", "var1=aaaa&var2=bbbbb"); var Target_LINK = prompt("Enter destination", location.href); function post(path, params) { var xForm = document.createElement("form"); xForm.setAttribute("method", "post"); xForm.setAttribute("action", path); for (var key in params) { if (params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); xForm.appendChild(hiddenField); } } var xhr = new XMLHttpRequest(); xhr.onload = function () { alert(xhr.responseText); }; xhr.open(xForm.method, xForm.action, true); xhr.send(new FormData(xForm)); return false; } parsed_params = {}; my_params.split("&").forEach(function (item) { var s = item.split("="), k = s[0], v = s[1]; parsed_params[k] = v; }); post(Target_LINK, parsed_params); void(0);
That's all! Now you can visit any website, and click that button in BOOKMARK BAR!
NOTE:
The above method sends data using XMLHttpRequest method, so, you have to be on the same domain while triggering the script. That's why I prefer sending data with a simulated FORM SUBMITTING, which can send the code to any domain - here is code for that:
javascript:var my_params=prompt("Enter your parameters","var1=aaaa&var2=bbbbb"); var Target_LINK=prompt("Enter destination", location.href); function post(path, params) { var xForm= document.createElement("form"); xForm.setAttribute("method", "post"); xForm.setAttribute("action", path); xForm.setAttribute("target", "_blank"); for(var key in params) { if(params.hasOwnProperty(key)) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); xForm.appendChild(hiddenField); } } document.body.appendChild(xForm); xForm.submit(); } parsed_params={}; my_params.split("&").forEach(function(item) {var s = item.split("="), k=s[0], v=s[1]; parsed_params[k] = v;}); post(Target_LINK, parsed_params); void(0);
I have faced similar problem, using the same post and and this link I have resolved my issue.
var http = new XMLHttpRequest();
var url = "MY_URL.Com/login.aspx";
var params = 'eid=' +userEmailId+'&pwd='+userPwd
http.open("POST", url, true);
// Send the proper header information along with the request
//http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//http.setRequestHeader("Content-Length", params.length);// all browser wont support Refused to set unsafe header "Content-Length"
//http.setRequestHeader("Connection", "close");//Refused to set unsafe header "Connection"
// Call a function when the state
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
This link has completed information.
Try to use json object instead of formdata. below is the code working for me. formdata doesnot work for me either, hence I came up with this solution.
var jdata = new Object();
jdata.level = levelVal; // level is key and levelVal is value
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "http://MyURL", true);
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.send(JSON.stringify(jdata));
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
}
There's some duplicates that touch on this, and nobody really expounds on it. I'll borrow the accepted answer example to illustrate
http.open('POST', url, true);
http.send('lorem=ipsum&name=binny');
I oversimplified this (I use http.onload(function() {}) instead of that answer's older methodology) for the sake of illustration. If you use this as-is, you'll find your server is probably interpreting the POST body as a string and not actual key=value parameters (i.e. PHP won't show any $_POST variables). You must pass the form header in to get that, and do that before http.send()
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
If you're using JSON and not URL-encoded data, pass application/json instead
var util = {
getAttribute: function (dom, attr) {
if (dom.getAttribute !== undefined) {
return dom.getAttribute(attr);
} else if (dom[attr] !== undefined) {
return dom[attr];
} else {
return null;
}
},
addEvent: function (obj, evtName, func) {
//Primero revisar attributos si existe o no.
if (obj.addEventListener) {
obj.addEventListener(evtName, func, false);
} else if (obj.attachEvent) {
obj.attachEvent(evtName, func);
} else {
if (this.getAttribute("on" + evtName) !== undefined) {
obj["on" + evtName] = func;
} else {
obj[evtName] = func;
}
}
},
removeEvent: function (obj, evtName, func) {
if (obj.removeEventListener) {
obj.removeEventListener(evtName, func, false);
} else if (obj.detachEvent) {
obj.detachEvent(evtName, func);
} else {
if (this.getAttribute("on" + evtName) !== undefined) {
obj["on" + evtName] = null;
} else {
obj[evtName] = null;
}
}
},
getAjaxObject: function () {
var xhttp = null;
//XDomainRequest
if ("XMLHttpRequest" in window) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhttp;
}
};
//START CODE HERE.
var xhr = util.getAjaxObject();
var isUpload = (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload));
if (isUpload) {
util.addEvent(xhr, "progress", xhrEvt.onProgress());
util.addEvent(xhr, "loadstart", xhrEvt.onLoadStart);
util.addEvent(xhr, "abort", xhrEvt.onAbort);
}
util.addEvent(xhr, "readystatechange", xhrEvt.ajaxOnReadyState);
var xhrEvt = {
onProgress: function (e) {
if (e.lengthComputable) {
//Loaded bytes.
var cLoaded = e.loaded;
}
},
onLoadStart: function () {
},
onAbort: function () {
},
onReadyState: function () {
var state = xhr.readyState;
var httpStatus = xhr.status;
if (state === 4 && httpStatus === 200) {
//Completed success.
var data = xhr.responseText;
}
}
};
//CONTINUE YOUR CODE HERE.
xhr.open('POST', 'mypage.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
if ('FormData' in window) {
var formData = new FormData();
formData.append("user", "aaaaa");
formData.append("pass", "bbbbb");
xhr.send(formData);
} else {
xhr.send("?user=aaaaa&pass=bbbbb");
}
This helped me as I wanted to use only xmlHttpRequest and post an object as form data:
function sendData(data) {
var XHR = new XMLHttpRequest();
var FD = new FormData();
// Push our data into our FormData object
for(name in data) {
FD.append(name, data[name]);
}
// Set up our request
XHR.open('POST', 'https://example.com/cors.php');
// Send our FormData object; HTTP headers are set automatically
XHR.send(FD);
}
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript
Short & modern
You can catch form input values using FormData and send them by fetch
fetch(form.action, {method:'post', body: new FormData(form)});
function send() {
let form = document.forms['inputform'];
fetch(form.action, {method:'post', body: new FormData(form)});
}
<form name="inputform" action="somewhere" method="post">
<input value="person" name="user">
<input type="hidden" value="password" name="pwd">
<input value="place" name="organization">
<input type="hidden" value="key" name="requiredkey">
</form>
<!-- I remove type="hidden" for some inputs above only for show them --><br>
Look: chrome console>network and click <button onclick="send()">send</button>
Just for feature readers finding this question. I found that the accepted answer works fine as long as you have a given path, but if you leave it blank it will fail in IE. Here is what I came up with:
function post(path, data, callback) {
"use strict";
var request = new XMLHttpRequest();
if (path === "") {
path = "/";
}
request.open('POST', path, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.onload = function (d) {
callback(d.currentTarget.response);
};
request.send(serialize(data));
}
You can you it like so:
post("", {orem: ipsum, name: binny}, function (response) {
console.log(respone);
})

jQuery function not getting called in mvc text-changed event

I am getting this strange behavior in jQuery when working with mvc application.
Below is MVC view in which I have implemented Text change event,
#Html.TextBoxFor(m => m.UserId, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.UserId, "", new { #class = "text-danger" })
$("#UserId").change(function () {
var UserId = $(this).val();
//$("#txtName").val(emailId);
$.ajax({
url: 'GetValidUserName',
type: 'POST',
data: JSON.stringify({ UserId: UserId }),
dataType: 'json',
contentType: 'application/json',
success: function (data) {
if (!$.trim(data)) {
alert("User does not exist in system. Please enter valid User Id.");
$(':input[type="submit"]').prop('disabled', true);
}
else {
$("#UserId").val(data);
$("#UserId").focus();
$(':input[type="submit"]').prop('disabled', false);
}
}
});
});
While debugging application when I load Index view directly first time , jQuery function gets called and invoke the controller action properly.http://localhost:51012/UserApplication/Index
But when I load the view again, jQuery function doesn't get called.
Controller code,
public JsonResult GetValidUserName(string userId)
{
LMTUsage objLMT = new LMTUsage();
LMTDAL objLMTDAL = new LMTDAL();
string UserID = "";
objLMT.UserList = objLMTDAL.GetAll_User("", 0, "6");
var AllUsersInDatabase = from p in objLMT.UserList
where p.UserId == userId
select new
{
Name = p.UserName,
Id = p.UserId,
};
foreach (var user in AllUsersInDatabase)
{
if (user.Name != null)
{
UserID = user.Id;
}
}
return Json(UserID, JsonRequestBehavior.AllowGet);
}
You have several issues with AJAX callback:
1) type: 'POST' option requires [HttpPost] attribute. If the attribute isn't present on the action method, use type: 'GET' instead.
2) You don't need JSON.stringify() to pass single parameter containing simple types (numeric and string values). A simple { userId: UserId } should be fine.
3) The controller action's parameter name must be exactly match with parameter name sent from AJAX callback.
Therefore, your AJAX callback should be follow example below:
$(function () {
$("#UserId").change(function () {
var UserId = $(this).val();
$.ajax({
url: '#Url.Action("GetValidUserName", "ControllerName")',
type: 'GET',
data: { userId: UserId },
dataType: 'json',
success: function (data) {
if (!$.trim(data)) {
alert("User does not exist in system. Please enter valid User Id.");
$(':input[type="submit"]').prop('disabled', true);
}
else {
$("#UserId").val(data);
$("#UserId").focus();
$(':input[type="submit"]').prop('disabled', false);
}
}
});
});
});

AjaxOptions.HttpMethod = GET results in method=POST

I have the following AjaxOptions object:
AjaxOptions ajaxOpts = new AjaxOptions
{
HttpMethod = "Get",
InsertionMode = InsertionMode.Replace
};
In the view I have this form:
#using (Ajax.BeginForm("GetPeopleData", ajaxOpts))
{
<div>
<button type="submit">Submit</button>
</div>
}
This results in the following HTML:
<form action="/People/GetPeopleData" data-ajax="true" data-ajax-method="Get" id="form0" method="post">
<div>
<button type="submit">Submit</button>
</div>
</form>
When I submit the form I can see that a GET request is sent.
Why does the HTML have data-ajax-method="Get" and method="post"?
What is the purpose of the method="post"?
The #Ajax.BeginForm() helper utilize jQuery unobtrusive AJAX library. If you examine the helper return type, it returns System.Web.Mvc.Html.MvcForm, the same return type as #Html.BeginForm() which creates <form> tag:
public static MvcForm BeginForm(
this AjaxHelper ajaxHelper,
AjaxOptions ajaxOptions
)
Since all of its overloads don't have parameter which specify HTTP request in System.Web.Mvc.FormMethod enumeration, it uses default POST request like #Html.BeginForm() has, hence it also writes method="post" for default form method if unobstrusive AJAX script is disabled in client side.
The purpose of data-ajax-method attribute is to override default submit request behavior when unobtrusive AJAX enabled because its value set by AjaxOptions.HttpMethod property, and checked by asyncRequest() method inside unobtrusive AJAX library (see complete version of the script here):
function asyncRequest(element, options) {
var confirm, loading, method, duration;
confirm = element.getAttribute("data-ajax-confirm");
if (confirm && !window.confirm(confirm)) {
return;
}
loading = $(element.getAttribute("data-ajax-loading"));
duration = parseInt(element.getAttribute("data-ajax-loading-duration"), 10) || 0;
$.extend(options, {
type: element.getAttribute("data-ajax-method") || undefined, // here AJAX method is checked (GET or POST)
url: element.getAttribute("data-ajax-url") || undefined,
cache: (element.getAttribute("data-ajax-cache") || "").toLowerCase() === "true",
beforeSend: function (xhr) {
var result;
asyncOnBeforeSend(xhr, method);
result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(element, arguments);
if (result !== false) {
loading.show(duration);
}
return result;
},
complete: function () {
loading.hide(duration);
getFunction(element.getAttribute("data-ajax-complete"), ["xhr", "status"]).apply(element, arguments);
},
success: function (data, status, xhr) {
asyncOnSuccess(element, data, xhr.getResponseHeader("Content-Type") || "text/html");
getFunction(element.getAttribute("data-ajax-success"), ["data", "status", "xhr"]).apply(element, arguments);
},
error: function () {
getFunction(element.getAttribute("data-ajax-failure"), ["xhr", "status", "error"]).apply(element, arguments);
}
});
Note: You can see list of attributes which corresponds to each properties of AjaxOptions in this reference.

Change UpdateTargetId of Ajax.BeginForm() dynamically based on form submission result

I'd appreciate if someone could help.
I want to return different partial views based on user type:
[HttpPost]
public ActionResult Edit(ContractModel model)
{
if(ModelState.IsValid)
{
if (curUser.IsInputer) { .... return View("Contracts");}
else if(curUser.IsAuthorizer) { ..... return View("Details");}
}
return PartialView(model);
}
View:
#{
string updateRegion = "";
if (curUser.IsInputer)
{
updateRegion = "content";
}
else if (curUser.IsAuthorizer)
{
updateRegion = "mainPane";
}
}
<script>
function returnViewOnFailure(result) { //not firing on submission failure
$("#mainPane").html(result);
}
</script>
#using (Ajax.BeginForm("Edit", new AjaxOptions() { UpdateTargetId = updateRegion,
InsertionMode = InsertionMode.Replace,
OnFailure = "returnViewOnFailure" }))
{.........}
The problem is when ModetState.IsValid= false my function returnViewOnFailure is not firing.
I would like UpdateTargetId be "mainPane" if form submission fails (regardless of user type), otherwise it should depend on curUser.
EDIT:
So, as advised I'm using ajax call to sumbit the form:
<script>
var form = $('#contract_form');
form.submit(function (ev) {
$.ajax({
cache: false,
async: true,
type: "POST",
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
$("#content").html(data);
//How to check ModelState.IsValid and show errors?
}
});
ev.preventDefault();
});
Because the validation is done serverside you can set the statuscode of the response (Controller.Response).
If the validation does not succeed set it to 500 (internal server error) so the ajax.onfailure gets called. Put the validationerror logic (replacing divs content) in there. Or maybee you can even change the updatetargetid in the onfailure (by javascript).

HTML not being generated in View's foreach loop using MVC 4

I am using AJAX to call an ActionResult and return a list of files. The data is stored in a dictionary object in the model then passed to the view. I have a foreach loop in the view that checks to see if the object is null. If not, it loops through the dictionary and produces table rows for each key/value pair. The problem is, the HTML is never generated and nothing is displayed. Using Firebug I have stepped through the entire process and everything is returned as it should be. Any help finding out why would be appreciated.
The AJAX:
function () {
$.ajax({
url: '#Url.Action("GetExpenseReportUploads", "MyExpenseReports")',
type: "GET",
async: true,
cache: false,
data: { DirectoryName: "ER_#=EPR_ID#" },
success: function() {
alert("success!");
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
}
The Controller:
public ActionResult GetExpenseReportUploads(string DirectoryName)
{
ExpenseReport.MVC.Models.MyExpenseReports model = new MyExpenseReports();
IEnumerable<string> fileArray = Directory.EnumerateFiles(Server.MapPath("~/Files/" + DirectoryName + "/")).Select(fn => "~/Files/" + DirectoryName + "/" + Path.GetFileName(fn));
//model.EPR_Uploads = Path.GetFileName(fileArray);
Dictionary<string, string> fileNames = new Dictionary<string, string>();
foreach (string filePath in fileArray)
{
string fileName = Path.GetFileName(filePath);
fileNames.Add(filePath, fileName);
model.EPR_Uploads = fileNames;
}
model.EPR_Upload_DirectoryName = DirectoryName;
return View(model);
}
The View:
<table>
#if (Model.EPR_Uploads != null)
{
foreach (KeyValuePair<string, string> upload in Model.EPR_Uploads)
{
<tr>
<td>
#using (Html.BeginForm("DeleteUpload", "MyExpenseReports", FormMethod.Post))
{
#Html.HiddenFor(m => m.FileId, new { #value = #upload.Value })
#Html.HiddenFor(m => m.EPR_Upload_DirectoryName)
}
<input type="submit" id="DeleteUploadBtn" value="Delete File" formaction="#Url.Action("DeleteUpload", "MyExpenseReports", new { FileId = #upload.Value, EPR_ID = "#=EPR_ID#", DirectoryName = Model.EPR_Upload_DirectoryName })" />
</td>
<td>
</td>
<td>
</td>
</tr>
}
}
You're mixing server-side processing and client-side processing. If you want the table to be built after your client-side AJAX call, you don't want to use the server-side model (Model.EPR_Uploads).
Instead, use a post-load client call to build the HTML. For example:
function () {
$.ajax({
url: '#Url.Action("GetExpenseReportUploads", "MyExpenseReports")',
type: "GET",
async: true,
cache: false,
data: { DirectoryName: "ER_#=EPR_ID#" },
success: function(data, textStatus, jqXHR) {
$("#tableId").append("<tr><td>" + data.EPR_Upload_DirectoryName + "</td></tr>";
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
You'll need to change your Controller to return data in JSON so you can properly parse it on the client side.
Hopefully this helps.

Resources