MVC Parallel transactions and session objects - asp.net-mvc

I can't get the session values when I start a different operation while an operation is in progress like below;
$.ajax({
type: 'GET',
cache: false,
url: '/Home/StartOperation',
dataType: 'json',
data: { customerId: $("#txtCustomerId").val() },
error: function (xhr, status, error) {
$("#textlabel").text(error)
},
success: function (result) {
$("#textlabel").text(result.Result)
}
});
Controller side;
public ActionResult StartOperation(string customerId)
{
Session["OperationId"] = "operationid";
// Some web api transactions (This operations takes a few minutes.)
var data = new { Result = "Operation Completed." };
return Json(data, JsonRequestBehavior.AllowGet);
}
I am sure about Session["OperationId"] is not null, and then I call my cancel action while web api transactions in progress;
$(function () {
$('#btnCancelLogin').on('click', function () {
$.ajax({
type: 'GET',
cache: false,
url: '/Home/CancelOperation'
});
});
});
Controller side;
public ActionResult CancelOperation()
{
String operationId = Session["OperationId"] as String // return null
//Cancel operations
}
Why Session["OperationId"] is always null on CancelOperation() method ? Thanks for advices.

if you take data from ajax side for start operation you should use post. Actually your ajax type is incorrect.
$.ajax({
type: 'POST',
cache: false,
url: '/Home/StartOperation',
dataType: 'json',
data: { customerId: $("#txtCustomerId").val() },
error: function (xhr, status, error) {
$("#textlabel").text(error)
},
success: function (result) {
$("#textlabel").text(result.Result)
}
});
Or if you want to take data from controller you should return data
public ActionResult StartOperation(string customerId)
{
Session["OperationId"] = "operationid";
// Some web api transactions
return json(customerId);
}
also your ajax should be like this
$.ajax({
type: 'GET',
cache: false,
url: '/Home/StartOperation',
dataType: 'json',
data: { customerId: $("#txtCustomerId").val() },
error: function (xhr, status, error) {
$("#textlabel").text(error)
},
success: function (result) {
$("#textlabel").text(result.Result)
}
});

Related

jquery ajax always get error section when try to pass json object(simple)

var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '#Url.Action("gettestjsn","Cart")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(jso),
success: function (data) {
alert(data.namep);
},
error: function () { alert("err"); }
});
this code always go to error function and i does not fire my mvc action,aslo i have a prop class which does match to this json obj. why is that i m new to json and jquery ajax please help
this is my action
public ActionResult gettestjsn(jso jso)
{
//do some here
return View();
}
Remove contentType from the ajax attributes and add
dataType: 'json',
This will work if the url is correct
this is how your code should look like
var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '#Url.Action("gettestjsn","Cart")',
data: jso,
success: function (data) {
alert(data.namep);
},
error: function () { alert("err"); }
});
Also i would refrain from using alerts. Either use console.log or debug using the inspector in your browser (comes inbuilt with chrome) to see what your data from the server looks like.
Try like this,
var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '/Cart/gettestjsn',
contentType: 'application/json; charset=utf-8',
data: jso,
success: function (data) {
alert(data.namep);
},
error: function (jqxhr, status, error) { alert("err:" + status + ':' + error); }
});
and your action should be,
[HttpPost]
public ActionResult gettestjsn(jso jso)
{
//do some here
return View();
}
Hope it helps.

Passing Multiple Checkbox value using jquery ajax

I am displaying multiple records on my ASP.NET MVC 4 view where each record has a checkbox. I want the user to be able to select multiple records (by checking checkboxes) and click Delete button in order to delete them. So far I can call the Delete Action method via jquery ajax but the problem is my action method does not seem to be accepting the passed array.
Here is my jquery code:
$(function () {
$.ajaxSetup({ cache: false });
$("#btnDelete").click(function () {
$("#ServicesForm").submit();
});
$("#ServicesForm").submit(function () {
var servicesCheckboxes = new Array();
$("input:checked").each(function () {
//console.log($(this).val()); //works fine
servicesCheckboxes.push($(this).val());
});
$.ajax({
url: this.action,
type: this.method,
data: servicesCheckboxes,
success: function (result) {
if (result.success) {
}
else {
}
}
});
return false;
});
});
and here is my action method:
[HttpPost]
public ActionResult DeleteServices(int[] deleteservice)
{
if (deleteservice != null)
{
//no hit
}
}
What am I missing?
Edit
I also tried console.log(servicesCheckboxes); before $.ajax() which outputs ["3", "4"] but still get null when I pass data as specified in answer below data: { deleteservice: servicesCheckboxes }. Even I tried data: [1,2] but still action method shows null for deleteservice in action method.
Just pass the array to your action:
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
data: { deleteservice: servicesCheckboxes }, // using the parameter name
success: function (result) {
if (result.success) {
}
else {
}
}
});
Or, just use the serialize() jquery method to serialize all fields inside your form:
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
data: $(this).serialize(),
success: function (result) {
if (result.success) {
}
else {
}
}
});
In your controller:
[HttpPost]
public ActionResult DeleteServices(int[] deleteservice)
{
bool deleted = false;
if (deleteservice != null)
{
// process delete
deleted = true;
}
return Json(new { success = deleted });
}
Finally got it working. "MVC detects what type of data it receive by contentType" as explained here so I made the following changes to $.ajax()
$.ajax({
url: this.action,
type: this.method,
dataType: "json"
//data: { deleteservice: servicesCheckboxes }, // using the parameter name
data: JSON.stringify({ deleteservice: servicesCheckboxes }),
contentType: 'application/json; charset=utf-8',
success: function (result) {
if (result.success) {
}
else {
}
}
});

Ajax call to controller method not passing parameter

I am trying to make an AJax call to a controller method the parameter is null no matter what I try. I have followed all the similar SO posts but to no avail. Sorry if the answer is there, I cant find it. The code I have is...
Ajax Call
var sguid = $(nTr).attr('id');
$.ajax({
url: "/Dashboard/Reporting/GetBlacklistedSoftwareItems",
type: 'POST',
dataType: 'json',
data: JSON.stringify({guid: sguid}),
statusCode: {
404: function() {
alert("page not found");
}
},
success: function (data) {
//DO Something
},
error: function () {
alert("error");
}
});
Controller Method
public JsonResult GetBlacklistedSoftwareItems(string guid)
{
List<DeviceSoftware> ldevice = new List<DeviceSoftware>();
Guid i = Guid.Parse(guid);
ReportMethods reportingMethods = new ReportMethods();
ldevice = reportingMethods.GetNonCompliantApplicationReport(CompanyId);
DeviceSoftware ds = ldevice.Find(x => x.Device.Guid == i);
List<DeviceApplication> da = new List<DeviceApplication>();
if (ds != null)
{
da = ds.DeviceApplications;
}
return Json(da, JsonRequestBehavior.AllowGet);
}
The method is being hit its just guid is alway null. sguid does hold the data I am trying to pass.
Can someone tell me what I am missing?
Against everything I read I changed
data: JSON.stringify({guid: sguid}),
To
data: {guid: sguid},
Now working.
Fred,
You need to make GetBlacklistedSoftwareItems a post method....
try this...
[HttpPost]
public JsonResult GetBlacklistedSoftwareItems(string guid)
{
Small changes needs to be done.
var sguid = $(nTr).attr('id');
$.ajax({
url: "/Dashboard/Reporting/GetBlacklistedSoftwareItems",
contentType: "application/json; charset=utf-8" ,//This is very important
type: 'POST',
dataType: 'json',
Data: JSON. stringify ({guild: squid}),
statusCode: {
404: function() {
alert("page not found");
}
},
success: function (data) {
//DO Something
},
error: function () {
alert("error");
}
});
Add the contentType: "application/json; charset=utf-8" , to the $.Ajax Call.
:)

ASP MVC 3 submit url parameters using AJAX and JQUERY

I've got a problem using ASP.NET MVC3, AJAX and JQUERY. I've got the following function
[HttpPost]
public bool Update(int id, FormCollection collection)
This is my jQuery Source:
$(document).ready(function () {
$('#btnUpdate').click(function (e) {
// Cancel default action
e.preventDefault();
var formCollection = $('#formId').serialize();
$.ajax({
cache: false,
type: 'POST',
url: '#Url.Action("Action","Controller")',
data: { id: $('#id').val(), collection: formCollection },
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error during process: \n' + xhr.responseText);
}
});
});
});
The id parameter submitted successfully, but the collection (FormCollection) includes an array with {[0]: 10000, [1]: collection}. I can't fix the problem. When I redesign the solution like this:
[HttpPost]
public bool Update(FormCollection collection)
$(document).ready(function () {
$('#btnUpdate').click(function (e) {
// Cancel default action
e.preventDefault();
$.ajax({
cache: false,
type: 'POST',
url: '#Url.Action("Action", "Controller")',
data: $('#formId').serialize(),
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error during process: \n' + xhr.responseText);
}
});
});
});
everything works fine. What I'm doing wrong in passing 2 parameter?
THX!!!
Try calling JSON.stringify() on your JSON:
data: JSON.stringify({ id: $('#id').val(), collection: formCollection })
$(document).ready(function () {
$('#btnUpdate').click(function (e) {
// Cancel default action
e.preventDefault();
var formCollection = $('#formId').serialize();
$.ajax({
cache: false,
type: 'POST',
url: '#Url.Action("Action","Controller")',
data: JSON.stringify({ id: $('#id').val(), collection: formCollection }),
success: function (data) {
alert(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error during process: \n' + xhr.responseText);
}
});
});
});
you should have to pass the data with jsonstringify
This is the actual watch:
Parameter ID submitted successfully (Name=id, Wert=10000). Above id you can see formCollection including FORM.serialize() values of the ajax call. But the System.Web.Mvc.FormCollection including two keys only: id and collection! I expected
"Name"
"Address"
"Address_2"
...
I think if got a mistake in creating my ajax request, but I don't know why...
var customerNo = $('#fieldID').val();
var formCollection = $('#formID').serialize();
$.ajax({
cache: false,
type: 'POST',
url: '#Url.Action("Action", "Controller")',
data: { id: customerNo, collection: formCollection },
dataType: 'json',
success: function (data) {
if (data) {
alert(data);
};
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error during process: \n' + xhr.responseText);
}
});
The following line generates an error:
data: JSON.stringify({ id: customerNo, collection: formCollection })
The parameters dictionary contains a null entry 'id' of non-nullable type 'System.Int32'...
Changed without effect:
data: { id: customerNo, collection: JSON.stringify(formCollection) },
Any ideas?
This is my idea (works!)
Add in a partial class from a model an string attribute, add this attribute manually in "data".
JS:
$.ajax({
cache: false,
type: 'POST',
url: '#Url.Action("Action", "Controller")',
data: $("form").serialize() + "&id=whatever",
dataType: 'json',
success: function (data) {
if (data) {
alert(data);
};
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error during process: \n' + xhr.responseText);
}
});
partialClass.cs Model:
public partial class TableName
{
public string id { get; set; }
}
Controller:
[HttpPost]
public bool Update(FormCollection collection){
var ID = collection.id;
}
Regards!

Will the error be displayed?

I have an ajax post and in the controller I return nothing. In case there is a failure will the error message displayed with the follwoing code?
[AcceptVerbs(HttpVerbs.Post)]
public void Edit(Model model)
{
model.Save();
}
$.ajax({
type: "POST",
url: '<%=Url.Action("Edit","test") %>',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function() {
},
error: function(request, status, error) {
alert("Error: " & request.responseText);
}
});
I would recommend you returning an empty result:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Model model)
{
model.Save();
return new EmptyResult();
}
also no need to specify data type:
$.ajax({
type: "POST",
url: '<%=Url.Action("Edit","test") %>',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: function() {
},
error: function(request, status, error) {
alert("Error");
}
});
In case the server returns a status code different than 200 the error callback will be called.

Resources