sending data from js over wire to the controller - javascript

Inside js function I'm creating javascript object which I then send to the mvc controller using ajax
var ab = { id: 100, name: "abc" }
$.ajax({
type: "POST",
url: "/home/dosomething",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(ab),
success: function (result) {
$("#myDiv").html(result);
$("#showModal").modal("show");
},
error: function () {
alert("error!");
}
});
on server side I have
[HttpPost]
public ActionResult DoSomething(string ab)
{
... ab is always null
}
I'm guessing that I should using some other data type as expected in controller method instead of string?

You need to use id and name in your action method
[HttpPost]
public ActionResult DoSomething(int id, string name)
{
//code
}

Try this:
JS:
var ab = { Id: 100, Name: "abc" }
$.ajax({
type: "POST",
url: "/home/dosomething",
dataType: "json",
data: JSON.stringify({ ab: ab }),
success: function (result) {
$("#myDiv").html(result);
$("#showModal").modal("show");
},
error: function () {
alert("error!");
}
});
Controller:
[HttpPost]
public ActionResult DoSomething(YourClass ab)
{
. . .
}
Model:
public class YourClass
{
public int Id { get; set; }
public string Name { get; set; }
}

Make a class of the JSON object, peg it as Serializable
[Serializable]
public class SomeClass
{
public int id { get; set; }
public string name { get; set; }
}
In your controller, you can now accept this as:
[HttpPost]
public ActionResult DoSomething([FromBody] SomeClass someclass){
// code
}

var ab = { id: 100, name: "abc" }
$.ajax({
type: "POST",
url: "/home/dosomething",
dataType: "json",
contentType: "application/json",
// what if you pass data like this
data: JSON.stringify({ab:ab}),
success: function (result) {
$("#myDiv").html(result);
$("#showModal").modal("show");
},
error: function () {
alert("error!");
}
});

If you want to send { id: 100, name: "abc" } as a string to the controller you need to change the data in ajax call to
data: JSON.stringify({ab:ab}),
if you want to send id and name as separate paramamters change your controller to
public ActionResult DoSomething(string id, string name)
{
}
and your ajax call data to
data: '{ "id":" 100 ","name":"abc" }',

Related

Cannot pass a object to a controller method with popup

From an ajax call I get some data which I want to pass to another window in a button click. I receive the data successfully but when that data is passed, in controller methods parameter is receiving the value as null.
<script>
$(document).ready(function () {
$('#btnSalesInAmount').click(function () {
var data = {
toDate: $('#todatepicker').val(),
fromDate: $('#fromdatepicker').val(),
customerId: $('#CustomerId').val()
};
$.ajax({
type: 'Get',
url: '/Reports/SalesInAmount' + '?toDate=' + data.toDate + '&fromDate=' + data.fromDate + '&customerId=' + data.customerId,
data: data,
success: function (data) {
window.open("/Reports/SalesInAmountView" + '?salesInAmount=' + data, 'SalesInAmountViewWindow', "features");// the data is not received by controllers method
}
});
});
});
</script>
in controller
public ActionResult SalesInAmountView(SalesInAmount salesInAmount) // parameter value is null
{
return View();
}
the model
public class SalesInAmount
{
public DateTime SalesDt { get; set; }
public int SalesSl { get; set; }
public int CustomerSupplyId { get; set; }
public string CustomerSupplyNm { get; set; }
public double TotalSalesByCustomer { get; set; }
public double TotalDiscount { get; set; }
public double TotalVat { get; set; }
public double TotalSales { get; set; }
public List<SalesInAmount> List { get; set; }
}
Try this ,
Simplify Your Data Set ,
var Param1= $('#ID').val();
var Data = JSON.stringify({ Data1 : Param1, . . });
Ajax
$.ajax({
url: '#Url.Action("Action_Name", "Controller_Name")',
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
data: Data,
cache: false,
success: function (data) {
});
}, error: function (request, status, error) {
}
});
}
Controller
public JsonResult Action_Name(string Data1 , . . )
{
return Json(Some_Json);
}
Note : this Controller Return Json Result , It depends on requirement .
You need to stringify the javascript object before pass as the parameter , JSON.stringify() is the function in javascript
<script>
$(document).ready(function () {
$('#btnSalesInAmount').click(function () {
var data = {
toDate: $('#todatepicker').val(),
fromDate: $('#fromdatepicker').val(),
customerId: $('#CustomerId').val()
};
$.ajax({
type: 'Post',
url: '/Reports/SalesInAmount',
data: JSON.stringify(data),
success: function (data) {
window.open("/Reports/SalesInAmountView" + '?salesInAmount=' + data, 'SalesInAmountViewWindow', "features");// the data is not received by controllers method
}
});
});
});
Make sure you have given same name of variable as you modal class SalesInAmount.
[HttpPost]
public ActionResult SalesInAmountView(SalesInAmount salesInAmount) // parameter value is null
{
return View();
}

Passing an object with values from View to ActionResult using ajax

I want to send an object from view to controller, ajax hits the action result but data is not being delivered to action result
View:
function submit()
{
var obj = {};
obj.PD = getResult('pd');
obj.MD = getResult('md');
obj.C = getResult('c');
obj.ME = getResult('me');
obj.EE = getResult('ee');
obj.SED = getResult('sed');
obj.RT = getResult('rt');
obj.SEA = getResult('sea');
$.ajax({
url: '/Assessment/AssessNow',
type: 'POST',
async: false,
data: '{obj' + JSON.stringify(obj) + '}',
dataType: 'json',
success: function (res) {
},
error: function (msg) {
}
});
//alert(getResult('pd'));
}
Model:
public class QAViewModel
{
public string C { get; set; }
public string EE { get; set; }
public string MD { get; set; }
public string ME { get; set; }
public string PD { get; set; }
public string RT { get; set; }
public string SEA { get; set; }
public string SED { get; set; }
}
Controller:
Editing as a good point was raised:
In the post you can just pass the full object like so:
function submit()
{
var obj = {};
obj.PD = getResult('pd');
obj.MD = getResult('md');
obj.C = getResult('c');
obj.ME = getResult('me');
obj.EE = getResult('ee');
obj.SED = getResult('sed');
obj.RT = getResult('rt');
obj.SEA = getResult('sea');
$.ajax({
url: '/Assessment/AssessNow',
type: 'POST',
async: false,
data: obj,
success: function (res) {
},
error: function (msg) {
}
});
//alert(getResult('pd'));
}
If you want to stick with json then modify your ajax call accordingly (you error was in the way you were building the data property:
$.ajax({
url: '/Assessment/AssessNow',
type: 'POST',
async: false,
data: JSON.stringify({obj: obj}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (res) {
},
error: function (msg) {
}
});
Also, depending on what you are doing with the result you may need to flip your controller actions to return JsonResult (Ignore if you are doing something such as returning a partial view to load):
[HttpPost]
public JsonResult Whatever(QAViewModel obj)
{
return Json(whatever, JsonRequestBehavior.AllowGet);
}

how to pass variable to property of model in mvc

I have a Model as below:
public class Class1
{
public int Id { get; set; }
public DateTime Start { get; set; }
}
and I have an ActionResult which is like this:
public ActionResult Create(Class1 model)
{
...
}
now, I want to fill Start property from another external javascript file using ajax like this:
$.ajax({
url: "/Admin/Create",
dataType: "Json",
type: "Post",
data: Start:"..."
});
How can I access to another View TextBox and fill that using ajax? What should I do in data on ajax?
Please try below code:-
var model = { Name :"Shyju",
Location:"Detroit",
Interests : ["Code","Coffee","Stackoverflow"]
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json"
}).done(function (res) {
$("#SomeDivToShowTheResult").html(res);
});
public class DashboardViewModel
{
public string Name {set;get;}
public string Location {set;get;}
public List<string> Interests {set;get;}
}
[HttpPost]
public PartialViewResult IndexPartial([FromBody] DashboardViewModel m)
{
return PartialView("_IndexPartial",m);
}

How to call Controller method of type HttpPost from Jquery ajax call

I am trying to call a controller function in MVC called UpudateFingerprintStatus from my jquery script. This is a PUT call because i'm updating the status of the desired object. I'm getting a 404 error when i'm trying to call this method.
Here is my JS code:
function updateStatus(statusId, fingerprintId, isDeleted, userId) {
var confirm = window.confirm("Are you sure you wish to change the Fingerprint Status?");
if (confirm) {
$.ajax({
type: "POST",
url: "/Tools/FingerprintTool/UpdateFingerprintStatus",
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
userId: userId,
statusId: parseInt(statusId),
fingerprintId: fingerprintId,
isDeleted: isDeleted
}),
sucess: function(resp) {
alert("success");
},
error: function(resp) {
alert("Failure" + resp.description);
}
});
}
}
And here is my Controller method:
[HttpPut]
public JsonResult UpdateFingerprintStatus(int userId, int statusId, int fingerprintId, int isDeleted)
{
var response = _driver.UpdateFingerprintGrantById(userId, fingerprintId, isDeleted, statusId);
return Json(response.Note);
}
Any help would be greatly appreciated!
When we send post , put request it sends complex data type in body so to bind that complex data you need to create class in which all properties should have same name as you sending from front-end.
public class FingerprintStatus{
public string UserId { get; set; }
public int StatusId { get; set; }
public int FingerprintId { get; set; }
public bool IsDeleted { get; set; }
}
[HttpPut]
public JsonResult UpdateFingerprintStatus(FingerprintStatus model)
{
var response = _driver.UpdateFingerprintGrantById(model.UserId, model.FingerprintId, model.IsDeleted, model.StatusId);
return Json(response.Note);
}
This should work:
function updateStatus(statusId, fingerprintId, isDeleted, userId) {
var confirm = window.confirm("Are you sure you wish to change the Fingerprint Status?");
if (confirm) {
var domain = window.location.protocol + "//" + window.location.host;
var url = domain + "/Tools/FingerprintTool/UpdateFingerprintStatus";
var dataContract = {
userId: userId,
statusId: parseInt(statusId),
fingerprintId: fingerprintId,
isDeleted: isDeleted
};
$.ajax({
type: "PUT",
url: url,
dataType: "json",
data: dataContract,
sucess: function(resp) {
alert("success");
},
error: function(resp) {
alert("Failure" + resp.description);
}
});
}
}
[HttpPut]
public JsonResult UpdateFingerprintStatus(int userId, int statusId, int fingerprintId, int isDeleted)
{
var response = _driver.UpdateFingerprintGrantById(userId, fingerprintId, isDeleted, statusId);
return Json(response.Note);
}

Passing two parameters to another controller with js

This is a button passing parameter values to another controller. It works perfectly for passing one value to the CarController but when I pass two I see it passing in the vehicle page but the breakpoint on the CarController shows that the vin_num value passed but the stock_num is null
Passing one param, works perfectly.
Vehicle.js
$(".button").click(function () {
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
url: "/Cars/setD",
data: JSON.stringify({ vin_num: this.id }),
success: function (result) {
window.location.href = '/Cars/Index';
}
});
});
CarController.cs
public JsonResult setD(string vin_num)
{
Session["vin_num"] = vin_num;
return Json(true, JsonRequestBehavior.AllowGet);
}
What I tried, for passing two values.
$(".button").click(function () {
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
url: "/Cars/setD",
data: JSON.stringify({ vin_num: this.id, stock_num: this.id2 }),
success: function (result) {
window.location.href = '/Cars/Index';
}
});
});
CarController.cs
public JsonResult setD(string vin_num, string stock_num)
{
Session["vin_num"] = vin_num;
Session["stock_num"] = stock_num;
return Json(true, JsonRequestBehavior.AllowGet);
}
You can use the Route attribute:
[Route("api/car/{param}/{paramTwo}")]
public JsonResult GetSomething(int param, int paramTwo) {
}
You can find more information about Attribute Routing in the following link
http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
Create a class for the object then pass that object:
public class Stock
{
string vin_num { get; set; };
string stock_num { get; set; };
}
in controller:
public JsonResult setD(Stock stock)
{
and use it:
data: JSON.stringify(stock:{ vin_num: this.id, stock_num: this.id2 }),
Alternatively:
var mydata= {stock { vin_num: this.id, stock_num: this.id2 }};
...
data: JSON.stringify(mydata),

Categories

Resources