I want to be able to post json data that was created via a javascript function through the Ajax.ActionLink helper.
I am able to accomplish this through straight jQuery code, but I am going to be doing this in a lot of places and wanted to see if there was a more efficient way to do it within MVC.
Working jQuery code:
$(function () {
$("#delete-selected").click(function () {
var ids= getSelected('ItemGrid'); //this returns a string[]
var postData = { Ids: courseIds };
var url = '/Home/DeleteSelected';
$.ajax({
url: url,
traditional: true,
type: "Post",
dataType: 'json',
data: postData
});
});
});
Write a script that uses unobtrusive JavaScript hooks like data- attributes to store the settings.
HTML:
<div data-ajax-url='/Home/DeleteSelected'
data-ajax-post-data='{function name or json content}'>
....
</div>
JQuery Plugin
$(document).on("click","[data-ajax-url]", function(){
var postData = $(this).data("ajax-post-data");
var url = $(this).data("ajax-url");
$.ajax({
url: url,
traditional: true,
type: "Post",
dataType: 'json',
data: postData
});
}
If you are doing an ajax call and want to update html with MVC, I would normally return Partial View from my call.Then update the html of the current holder with the result
Server Side
public ActionResult DeleteSelected(int[] Ids)
{
//do something
MyModel model = new Model(); //create object with new data
return Partial("_PartialViewName", model);
}
Javascript
$("#delete-selected").click(function () {
var ids= getSelected('ItemGrid'); //this returns a string[]
var postData = { Ids: courseIds };
var url = '/Home/DeleteSelected';
$.ajax({
url: url,
traditional: true,
type: "Post",
dataType: 'html',
data: postData
success: function(result){
$('#MyPartialViewContainer').html(result);
}
});
});
Related
I have a view called InvoiceTo and a Controller called Order. Using JQuery, the default URL is: url: '', and this is the result:
locahost:port/domain/order/InvoiceTo
If I change the URL: url: /Order/GetInformation, this is the result:
locahost:port/domain/order/InvoiceTo/Order/GetInformation
I've already tried lots of way to set my url, but is always wrong. This is my JQuery:
$(document).ready(function () {
$('#InvoiceToDrop').change(function () {
var $div = $('#modalPartial');
var idcustomer = $(this).val();
$.ajax({
url: '/Order/GetInformation/' + idcustomer,
type: 'GET',
success: function (data) {
alert(JSON.stringify(data));
},
error: function (error) {
}
})
});
});
What I have to do to have this URL:
locahost:port/domain/Order/GetInformation/1
You can use the UrlHelper Url.Action method in the view:
$.ajax({
url: '#Url.Action("GetInformation", "Order", new { customerId })',
...
Or
url: '#Url.Action("GetInformation", "Order")/' + idcustomer
When the view loads #Url.Action is parsed and is replaced by the actual value.
Advantages of using this method are that it uses the routing table rather than statically typed urls.
here is my ajax method
fl = new FormData();
fl.append("abcd", $("#so_camera_click")[0].files[0]);
debugger;
$.ajax({
type: "POST",
url: "../SaleOrder/AddSaleOrderToDB",
dataType: "json",
traditional: true,
data: {
f:fl,
}});
and C# controller is
the id so_camera_click is <input type="file" accept="image/*"/> every time i debug javascript there is data in fl variable but when it hits back end c# controller it gets null
public JsonResult AddSaleOrderToDB(HttpPostedFileWrapper f)
{
}
In your ajax request,
Change the value of data as follows,
$.ajax({
type: "POST",
url: "../SaleOrder/AddSaleOrderToDB",
traditional: true,
processData: false,
contentType: false
data: fl
});
Use Proper, readable field names.
Your controller is expecting a File and not a JSON data.
You'll want to post FileData and not json.
Additionally, for the Controller to map your posted values the argument must have the same name as you have used for the POST.
So for your example to work you'll have to do something like this
fl = new FormData();
fl.append("file", $("#so_camera_click")[0].files[0]);
debugger;
$.ajax({
type: "POST",
url: "../SaleOrder/AddSaleOrderToDB",
data: fl,
contentType: false,
processData: false
});
And in your Controller
public JsonResult AddSaleOrderToDB(HttpPostedFileWrapper file)
{
}
I want to post with AJAX a string array with some data to my controller. It's just plain text, and my controller is always receiving a null parameter. I understand i shouldn't stringify since i don't use a model or viewmodel.
I searched other questions but most refer to forms and use viewmodel properties.
Here is my code:
Controller
[HttpPost]
public ActionResult FirstAjax(string[] listValues)
{
//TODO
return Json("Reached the controller", JsonRequestBehavior.AllowGet);
}
I added that JSON return to check if I was actually hitting the controller and I receive the message on my view.
AJAX POST
var listValues = [];
listElements.each(function (index, element) {
listValues.push(element.innerText);
});
var serviceURL = '/Products/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: listValues,
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
Since my list is sortable with drag & drop, the listValues is filled with the text value of the <li> items in the order when the button is clicked.
View
<div class="demo">
<ul id="sortable">
<li class="ui-state-default">Cat</li>
<li class="ui-state-default">Dog</li>
<li class="ui-state-default">Tiger</li>
</ul>
<button type="button" onclick="display_array();">Ajax Post!</button>
</div><!-- End demo -->
Write your Ajax POST method as follows:
$(document).ready(function(){
var listValues = [];
listElements.each(function (index, element) {
listValues.push(element.innerText);
});
var serviceURL = '/Products/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: {listValues: listValues},
contentType: 'application/json'
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
Hope this will solve your problem.
Change your ajax options to:
$.ajax({
...
data: {listValues: listValues},
...
});
the reason is: server is expecting a posted object/query string that's same naming with parameters. the data is converted to listValues=...&otherParams=... in query string. if you post an array without specifying parameter name, JQuery cannot map them correctly
You need contentType as application/json and use JSON.stringify to convert JavaScript object to JSON string.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: serviceURL,
data: JSON.stringify({ listValues: listValues}),
success: successFunc,
error: errorFunc
});
I'm posting data with ajax and it's successfully posted. At the controller side I'm filling a ViewBag with data posted but i'm having a problem getting data from ViewBag.
Here's Ajax Code:
$.ajax({
type: "POST",
url: '../Home/getExistUsersFromJSON',
data: JSON.stringify({ jsonString: JSON.stringify(array) }),
traditional: true,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function () {
// Alert that it was succesful!
var jsonList = '#Html.Raw(Json.Convert(ViewBag.newUsers))';
var jsList = JSON.parse(jsonList);
bootbox.dialog({
message: jsList,
title: "Utilisateurs",
buttons: {
success: {
label: "Success!",
className: "btn-success"
}
}
});
}
});
And this is the controller side
[ActionName("getExistUsersFromJSON")]
public void getExistUsersFromJSON(string jsonString)
{
IList<newUser> ctm =
new JavaScriptSerializer().Deserialize<IList<newUser>>(jsonString);
ViewBag.newUsers = ctm.ToList();
}
ViewBag is just an object that gets passed to the view when you render the page.
It doesn't make any sense to use that with AJAX; your server-side Razor code runs on initial server render only.
You need to server JSON as the response (using Json()).
I am passing data to controller through Ajax call.
Following is the ajax code:
var month_List = [];
$('#dojMonths :selected').each(function (i, selectedItem) {
month_List[i] = $(selectedItem).text();
});
var from_Month = $("#fromKPAMonthPicker").val();
var from_Year = $("#fromKPAYearPicker").val();
var to_Month = $("#toKPAMonthPicker").val();
var to_Year = $("#toKPAYearPicker").val();
$.ajax({
url: '/Home/_DataByFromTo',
type: "POST",
data: {
doj_Month_List: month_List,
from_Month: from_Month,
from_Year: from_Year,
to_Month: to_Month,
to_Year: to_Year
},
dataType: "html",
success: function (data) {
$("#divList").html(data);
}
});
Controller action method:
[HttpPost]
public ActionResult _DataByFromTo(List<Int32> doj_Month_List, Int16 from_Month, Int16 from_Year, Int16 to_Month, Int16 to_Year)
{
return View();
}
It was working in my old code perfectly fine. I don't know whats the problem. because all data are passing perfectly except this array of jquery.
To disable deep serialization of objects you need to set traditional property to true.
$.ajax({
url: '/Home/_DataByFromTo',
type: "POST",
data: {
doj_Month_List: month_List,
from_Month: from_Month,
from_Year: from_Year,
to_Month: to_Month,
to_Year: to_Year
},
dataType: "html",
traditional: true,
success: function (data) {
$("#divList").html(data);
}
});
When set to true it results in a shallow serialization.
Following link might be of help.
https://api.jquery.com/jQuery.param/
try using push
var month_List = [];
$('#dojMonths :selected').each(function (i, selectedItem) {
month_List.push($(selectedItem).text());
});