Pass array by ajax with MVC 4 - c#

I'm having problems to passa an Javascript array by ajax to my application. The ajax call is executing my server-side method but the parameter is null, and, even before my method finish processing, ajax throws error (execute its error function).
This is my ajax call:
<script>
var permissoesUsuario = Array();
$(function () {
//funcao de envio das permissoes
$('#btnSalvar').click(function () {
//desabilita o botao de salvar
$(this).attr('disabled', 'disabled');
$.each($('input[name="chkPermissao"]:checked'), function () {
permissoesUsuario.push({
IdEmpresa: $(this).attr('data-empresa'),
IdPermissao: $(this).attr('data-permissao')
});
});
$.ajax({
url: '#(Url.Content("~/Funcionario/Permissoes"))',
data: JSON.stringify(permissoesUsuario),
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (response) {
permissoesUsuario = Array();
if (response == '') {
window.location = '#(Url.Content("~/Funcionario"))';
}
},
error: function(){
console.log('Erro');
}
});
});
</script>
And my server-side method:
[HttpPost]
public ActionResult Permissoes(IList<PermissaoAcessoInputModel> permInput)
{
//Do something
}
My permInput variable is null..
This is my PermissaoAcessoInputModel Class:
public class PermissaoAcessoInputModel
{
public virtual int IdPermissao { get; set; }
public virtual ulong? IdEmpresa { get; set; }
}

Have you tried setting
traditional: true
In your AJAX options?
ex
$.ajax({
url: '#Url.Content("~/Funcionario/Permissoes")',
data: JSON.stringify(permissoesUsuario),
type: 'POST',
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (response) {
permissoesUsuario = Array();
if (response == '') {
window.location = '#Url.Content("~/Funcionario")';
}
},
error: function(){
console.log('Erro');
}
});

Related

How to show custom error message on forced error inside a JsonResult

I have a JsonResult where I do some validation and set the response status code to 400 and return a Json with a custom variable named errorMessage.
In the view I have the normal JQuery AJAX code, and in the error section I want to access to the value in the variable errorMessage.
How to declare the function() inside the error section in JQuery AJAX code.
// JsonResult action method
public JsonResult QuitarMiembro(string Id)
{
if (Id == null)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(new { errorMessage = "Null Id" });
}
}
//JQuery AJAX
function MyFun(Id) {
console.log(Id);
$.ajax({
type: "POST",
url: '#Url.Action("QuitarMiembro", "MiembrosJD")',
dataType: 'json',
data: { IdUsuario: Id },
success: function (data) {
fnMostrarMensajeExito(data.message);
tablaMiembrosJD.ajax.reload();
},
error: function (data) {
console.log(data.errorMessage);
}
});
}
try this code for error msg
function MyFun(Id) {
console.log(Id);
$.ajax({
type: "POST",
url: '#Url.Action("QuitarMiembro", "MiembrosJD")',
dataType: 'json',
data: { IdUsuario: Id },
success: function (data) {
fnMostrarMensajeExito(data.message);
tablaMiembrosJD.ajax.reload();
},
error: function (data) {
alert("Error:" + data.errorMessage);`
}
});
}

How to return a ajax response in c#?

I am new to AJAX and C#, So i am trying how to work them together. I am building a web application and I am invoking a method from c# in my ajax function and if everything works fine then I want to receive the success message back to my c# class. How can I do that?
This is my ajax method
<script type="text/javascript">
Hello();
function Hello() {
$.ajax({
type: "POST",
url: "Dtata.aspx/Hello",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
response(result.d);
},
error: function (result) {
alert('There is a problem processing your request');
}
});
}
</script>
//Basically I want to know the success/failure value from the Ajax call and print it back to my console.
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string Hello(string name)
{
return name;
}
have you tried to pass also the data in your ajax call? (string name) .. cause your back end service (webMethod) have it in its method param...something like:
<script type="text/javascript">
Hello();
function Hello() {
$.ajax({
type: "POST",
url: "Dtata.aspx/Hello",
contentType: "application/json; charset=utf-8",
dataType: "json",
data:{name:'hello'},
success: function (result) {
response(result.d);
Counter() //<-- CALL OTHER AJAX METHOD TO INCREASE COUNTER ON BACK END
},
error: function (result) {
alert('There is a problem processing your request');
}
});
}
function Counter() {
$.ajax({
type: "POST",
url: "Dtata.aspx/Counter",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
console.log(result.d);
},
error: function (result) {
alert('There is a problem processing your request');
}
});
}
</script>
//Basically I want to know the success/failure value from the Ajax call and print it back to my console.
private int _counter;
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string Hello(string name)
{
return name;
}
[WebMethod]
public static int Counter()
{
this._counter = this._counter +1;
return this._counter
}
You missed data in ajax call:
var counter=0;
$.ajax({
type: "POST",
url: "Dtata.aspx/Hello",
contentType: "application/json; charset=utf-8",
dataType: "json",
data:{name:"test"}
success: function (result) {
//result is response from c#. you can do your trick here
alert(result.d);
if(result.d=="success"){
counter++;
}
},
error: function (result) {
alert('There is a problem processing your request');
}
});

jQuery is not firing backend method in asp.net

I am firing Backend method of asp.net using jQuery. I have set everything perfectly as much i knew. But still don't know what is the wrong.
Please help me to solve this issue.
My Code :
<asp:Button ID="btnSubmit" runat="server" Text="Update" />
var jquery = $.noConflict();
jquery(document).ready(function() {
jquery("#<%=btnSubmit.ClientID%>").click(function() {
if(jquery("#form1").valid()) {
jquery.ajax({
type: "POST",
url: "Page.aspx/UpdateData",
data: jquery("#form1").serialize(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(msg) {
alert(msg);
}
});
}
});
});
Backend method :
[System.Web.Services.WebMethod]
public static string UpdateData(string get_param)
{
// Code...
}
I also tried to check by using BeakPoint but it is not going in code behind. Even, I can't see any error.
I removed content type. As you are using formSerialize. It will form data like key=value&key1=value1 and it is not json format so.
note: Make sure you have form with id form1 present.
jquery(document).ready(function() {
jquery("#<%=btnSubmit.ClientID%>").click(function() {
if(jquery("#form1").valid()) {
jquery.ajax({
type: "POST",
url: "Page.aspx/UpdateData",
data: '{ "get_param" :"' + $('form').serialize() + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(msg) {
alert(msg);
}
});
}
});
});
try to remove contentType from ajax request anf get dataa
public static string UpdateData(string get_param)
string get_params= HttpContext.Current.Request["get_param"];
}
If you want to send json data, convert your data to json format.
var jquery = $.noConflict();
jquery(document).ready(function() {
jquery("#<%=btnSubmit.ClientID%>").click(function() {
if(jquery("#form1").valid()) {
jquery.ajax({
type: "POST",
url: "Page.aspx/UpdateData",
data: JSON.stringify({ get_param:jquery("#form1").serialize() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(msg) {
alert(msg);
}
});
}
});
});
public class MyClass
{
public string myName
{
get { return "Hello"; }
}
}
In your aspx.cs page:
[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json, UseHttpGet = true)]
public static object MyMethod()
{
return new MyClass();
}
And in your ASPX page:
$.ajax({
url: "somepage.aspx/MyMethod",
data: {},
cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
type: "GET",
success: function (data) {
if (data.hasOwnProperty("d"))
alert(data.d.myName);
else
alert(data);
},
error: function (reponse) {
alert(reponse);
}
});
Issue was because of asp.net button. It was refreshing page after validation completion. So, I used preventDefault after button click in jquery and it has solved my issue.
Check my code :
function pageLoad() {
jquery('#<%= btnSubmit.ClientID %>').click(function (e) {
if(jquery("#form1").valid()) {
e.preventDefault(); // this line was imp
// Ajax call...
});
}

ajax pass object to controller

HomeController:
[HttpPost]
public JsonResult SetDefaultHomeCategoryOrder(CategoryOrderModel categories)
{
return Json(new { msg = "ok" });
}
public class CategoryOrderModel
{
public int DisplayOrder;
public int CategoryId;
}
View:
var operationCollection = new CategoryOrderModel();
$.ajax({
url: '#Url.Action("SetDefaultHomeCategoryOrder", "Home")',
dataType: 'json',
data: JSON.stringify(operationCollection),
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
The controller never gets the correct parameter??
UPDATED: I changed the code to accept the collection
[HttpPost]
public JsonResult SetDefaultHomeCategoryOrder(List<CategoryOrderModel> categories)
{
return Json(new { msg = 'ok' });
}
View:
var collection = [];
var col1= new CategoryOrderModel(1,2);
collection.push(col1);
var col2= new CategoryOrderModel(2,5);
collection.push(col2);
$.ajax({
url: '/Home/SetDefaultHomeCategoryOrder/',
dataType: 'json',
data: '{ categories : ' + JSON.stringify(collection) + '}',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
function CategoryOrderModel(displayOrder, categoryId) {
var self = this;
self.DisplayOrder = displayOrder;
self.CategoryId = categoryId;
}
Following are the errors in your code
1.Your model dont have getters and setters
public class CategoryOrderModel
{
public int DisplayOrder { get; set; }
public int CategoryId { get; set; }
}
2.Since it is javascript , operationCollection is model so it will not work instead deaclare a variable
var CategoryOrderModel =
{
"DisplayOrder": "7",
"CategoryId": "9"
};
$.ajax({
url: '#Url.Action("SetCategoryOrder", "Home")',
dataType: 'json',
data: '{ categories : ' + JSON.stringify(CategoryOrderModel) + '}',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
As we know MVC works on the principle of name/value pair i.e. on Strongly type view along with Model binding.
Possibly you can do:
$.ajax({
url: '#Url.Action("SetDefaultHomeCategoryOrder", "Home")',
dataType: 'json',
data: {'DisplayOrder' : 9 , 'CategoryId' : 1},
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.msg);
},
error: function (data) {
alert('error');
}
});
Notice data key/value data: {'DisplayOrder' : 9 , 'CategoryId' : 1},, this is somewhat similar to post a form in MVC.
Generally we use $('#formId').serialize() to send collection from view to controller with jquery/ajax.
You are trying to pass the data to controller "SetDefaultHomeCategoryOrder" or "SetCategoryOrder"
if Action name is SetCategoryOrder then type
url:#Url.Action('SetCategoryOrder','Home')
Your methods don't match from view you are calling SetDefaultHomeCategoryOrder but inside the controller it's called SetCategoryOrder

Return ViewModel Data to Javascript function MVC 4?

I am trying to pass the data of the view model to one js method and from there I need to pass the VM to another controller method to show the data.
here is what I have did:
$(document).ready(function () {
var content = GetHomeContent('/Home/CastContent');
if (content) {
saveBDContent('/Message/Details/', content);
}
});
function GetHomeContent(url) {
var modelData;
$.ajax({
url: url,
cache: false,
async: false,
type: "GET",
contentType: 'application/json',
success: function (data) {
if (data) {
modelData = data;
}
},
error: function (data) {
status = false;
}
})
return modelData;
};
function saveBDContent(url, data) {
var status = false;
$.ajax({
url: url,
cache: false,
async: false,
type: "GET",
data: JSON.stringify(data),
contentType: 'application/json',
success: function (data) {
if (data == "200") {
status = true;
}
},
error: function (data) {
status = false;
}
})
return status;
};
The problem am facing is , the content I retrived from the method show the namespace of the ViewModel. When I pass that to the new controlled the Viewmodel content is coming null.
Do I need to add anything to get/Pass the proper content ?
The Dummy method skeleton
public ActionResult CastContent()
{
CastVM broadcastVM = new CastVM();
return Json( broadcastVM);
}
I have missed out the JsonRequestBehavior.AllowGet in my controller method, I have added and the results are coming perfectly.
public ActionResult CastContent()
{
CastVM broadcastVM = new CastVM();
return Json( broadcastVM,JsonRequestBehavior.AllowGet);
}
and also I have set the HTTP status as post in the jquery method
Do something like that in the Controller:
public JsonResult QuickSave(BookEntry bookEntry) {
YourViewModel model = new YourViewModel();
return Json(model);
}
EDIT >> The associated Javascript code is :
$.ajax({
type: "POST",
url: 'The URL',
data: 'The JSON data',
dataType: "json",
success: function (theViewModel) {
// Do some JS stuff with your model
},
error: function (xhr, status, error) {
// Do some error stuff
}
});

Categories

Resources