pass value to controller by using ajax - c#

I want to pass value from view to controller by using ajax.
<button onclick="addCommentByAjax()" >Save</button>
My script:
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey',
data: {
choiceId: "1"
}
});
}
Controller:
[HttpPost]
public ActionResult DoDetailSurvey(SurveyViewModel model, string choiceId)
{
//
}
but choiceId always null

Change couple of things.
First assign an id or class to your button.Second remove inline onclick function and use ajax click function.Then specify the request type as Post.
$('#btnComment').click(function () {
var choiceId = $('#YourChoiceId').val();
$.ajax({
url: '/Survey/DoDetailSurvey',
data: { 'choiceId' : choiceId},
type: "post",
cache: false,
success: function (response) {
//do something with response
},
error: function (xhr, ajaxOptions, thrownError) {
alert('error occured');
}
});
});
Then your controller should look like this
[HttpPost]
public ActionResult DoDetailSurvey(string choiceId)
{
//
}
I don't know how you are populating your viewmodel,so I purposely removed them and shown an working example.
In case you want to pass viewmodel you should construct your data object like this:
var data = {};
data.Property1 = some val;
data.Property2 = "some val";
$.post('/Survey/DoDetailSurvey', data);
Sample structure of SurveyViewModel I assume:
public class SurveyViewModel
{
public int Property1 { get; set; }
public string Property2 { get; set; }
}

Since there are two parameter in your controller, you need to identify them both form the client side. Further, you should specify the contentType.
You spread the payload like so:
function addCommentByAjax() {
var payload = {
model: {
// whatever properties you might have
},
choiceId: 1
};
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey',
contentType: 'application/json',
data: JSON.stringify(payLoad)
});
}

function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey?choiceId=1'
}
});
}
You can also pass like this
or for more parameters
function addCommentByAjax() {
$.ajax({
type: "POST",
url: '/Survey/DoDetailSurvey?choiceId=1&Name=Arun'
}
});
}

Related

Unable to pass values to MVC Controller via AJAX

I have an MVC controller which takes an int and a complex object
[HttpPost]
public async Task<JsonResult> AddComment(int ticketId, TicketReply ticketReply)
Even if I take out the object, I can't seem to pass a simple value. Here's what the AJAX call looks like
var dataObject = {
ticketId: ticketId //, ticketReply: { Attachements: attachements }
};
$.ajax({
url: $('#updateTicketURL').val(),
data: dataObject, //, //JSON.stringify(dataObject), //JSON.stringify(dataObject),
type: 'POST',
//dataType: 'JSON',
contentType: 'application/json',
success: function (data) {
console.log(data);
}
})
I have tried every combination of JSON.stringyfy etc. but I never seem to get the value. Even if I replace with static values it never seems to work.
You need an object model that matches the data being sent
public class DataObject {
public int ticketId { get; set; }
public TicketReply ticketReply { get; set; }
}
next you update the controller action to expect the data using the [FromBody] attribute so that the model binder can create and populate the sent data
[HttpPost]
public async Task<JsonResult> AddComment([FromBody]DataObject dataObject) {
int ticketId = dataObject.ticketId;
TicketReply ticketReply = dataObject.ticketReply;
//...
}
Finally you need to send the data correctly from the client.
var dataObject = {
ticketId: ticketId ,
ticketReply: { Attachements: attachements }
};
$.ajax({
url: $('#updateTicketURL').val(),
data: JSON.stringify(dataObject),
type: 'POST',
dataType: 'JSON',
contentType: 'application/json',
success: function (data) {
console.log(data);
}
});

Passing json to mvc controller

I am trying to post some data via jQuery ajax to an Asp.Net MVC controller. I have the follow class which I am working with:
public class InnerStyle
{
[JsonProperty("color")]
public string HeaderColor { get; set; }
[JsonProperty("font-size")]
public string HeaderFontSize { get; set; }
[JsonProperty("font-family")]
public string HeaderFontFamily { get; set; }
}
The post method looks like:
public JsonResult UpdateRecord(InnerStyle innerStyle)
{
//Do some validation
return Json("OK");
}
And my jQuery looks like:
$('#font-size-ddl').change(function () {
var value = $(this).val();
headerObj["font-size"] = value;
console.log(JSON.stringify({ innerStyle: headerObj }));
$.ajax({
type: "POST",
url: "#Url.Action("UpdateRecord", "Document")",
data: JSON.stringify({ innerStyle: headerObj}),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
});
The console.log in the above change event produces the following JSON string:
{"innerStyle":{"text-align":"","font-size":"20px","color":""}}
Now the issue I am having is if I set a break point on my UpdateRecord Action and see what is coming through the innerStyle object is null. Can someone tell me where I am going wrong please.
I tried using the below code and it's working fine.
$.ajax({
type: "POST",
url: "#Url.Action("UpdateRecord", "Document")",
data: JSON.stringify({"text-align":"","font-size":"20px","color":""}),
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
I simply removed the parameter name "innerStyle". I just noticed one thing which might be a typo error. You are passing a property "text-align":"" instead of "font-family". So it's not populating all properties inside the controller's action UpdateRecord(InnerStyle innerStyle). You should pass similar to the below json object to map the entire object on controller's action UpdateRecord(InnerStyle innerStyle)
{
"color": "sample string 1",
"font-size": "sample string 2",
"font-family": "sample string 3"
}
#Code, your code is fine. It's just you cannot use [Json Property] while you are hitting controller via ajax. you have to use real class properties.
$('#font-size-ddl').change(function () {
var value = $(this).val();
var headerObj = {};
headerObj["HeaderColor"] = "Red";
headerObj["HeaderFontSize"] = value;
headerObj["HeaderFontFamily"] = "Arial";
console.log(JSON.stringify({ custom: headerObj }));
$.ajax({
type: "POST",
url: "#Url.Action("UpdateRecord", "Employee")",
traditional: true,
data: JSON.stringify({ custom: headerObj }),
dataType: JSON,
contentType: "application/json; charset=utf-8",
success: function (data) {
console.log(data);
}
});
});

JS Array is not received by c# webapi

I have a test js function that should post data to webapi by Post method
function test() {
var puffs = [];
var puffObject = {
id: "2735943",
priority: "1"
};
puffs.push(puffObject);
puffs.push(puffObject);
var dto =
{
po: puffs
};
$.ajax({
type: "POST",
url: "../api/PuffPriority/",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(dto),
dataType: "json",
success: function (data, status) {
if (data) {
console.log("Welcome");
} else {
console.log("No data");
}
},
error: function (error) {
console.log("Error");
}
});
}
In the controller class i have
public void Post(PuffPriority[] po){
//Do something here with po, but po is always empty
}
where PuffPriority Model is
public class PuffPriority
{
public string id { get; set; }
public string priority { get; set; }
}
I dont know whats wrong , the values are sent by JS but api Controller don't fetch it :( Please help, i have already wasted a lot of time.
You have a bug in your code.
Simply change
url: "../api/PuffPriority/"
to
url: "../api/Post/"
or change your method name from Post to PuffPriority
Changed
public void Post(PuffPriority[] po){
//Do something here with po, but po is always empty
}
To
[FromBody]List<PuffPriority> po{
//Do something here with po, but po is always empty
}

How to send javascript dictionary to controller method in MVC4

I have a js file that has to send a dictionary object to the server. My javascript part looks like that:
$.ajax({
url: "/ControllerName/ActionName",
type: 'post',
dataType: 'json',
data: myData
});
where myData is something like
this myData["favouritePet"] = "dog", myData["favouriteBook"] = "What?"
In the controller I have this:
[HttpPost]
public virtual ActionResult ActionName ( Dictionary<string, string> jsonFormattedData)
{
return null;
}
but when I debug it the parameter gets a null value every time. I tried to make the argument of type string but it is the same. Can you help me with that?
You are just passing JavaScript object, so you can use JSON.stringify and make the Model as Action parameter.
MVC Model Binder will convert it to your model.
public class MyDataModel
{
public string FavouritePet { get; set; }
public string FavouriteBook { get; set; }
}
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(MyDataModel myData)
{
return View();
}
<button id="btnSubmit" type="button">Submit</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$("#btnSubmit").click(function () {
var myData = new Object();
myData.favouritePet = "dog";
myData.favouriteBook = "What?";
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'POST',
dataType: 'json',
data: JSON.stringify(myData),
contentType: "application/json; charset=utf-8",
success: function (){}
});
});
</script>

Retrieving data from Ajax POST in asp.net

I have an ajax POST like this
$(document).ready(function () {
var pcontent = document.body.innerHTML;
var url = new URI();
$.ajax({
url: url,
type: "POST",
data: { "pcontent": pcontent },
success: function (data) {
alert($(data).find(".right-panel").html());
},
complete: function () {
},
error: function (jqXHR, error, errorThrown) {
if (jqXHR.status) {
alert(jqXHR.responseText);
} else {
alert("Something went wrong");
}
}
});
return false;
});
I am little confused how i could retrieve data (pcontent) that i post here in my code behind.actually in a specific class file i need to implement this logic .
You have to create a controller action:
public class HomeController: {
// model
public class PDocument {
public string pcontent {get;set;}
}
[HttpPost]
public ActionResult SaveDocument(PDocument pcontent){
// do something
return new JsonResult() { Data = new { Success = true } };
}
}
JS:
$.ajax({
url: "Home/SaveDocument",
type: "POST",
data: { "pcontent": pcontent}
...});
Note:
You don't need to create a model on server if set
$.ajax({
url: "Home/SaveDocument",
type: "POST",
data: pcontent
});
// server side
public ActionResult SaveDocument(string pcontent){
// do some thing
}
For security reason, your html must be encoded before calling ajax
In case you new to mvc, then this is a good way to start: http://www.asp.net/mvc/tutorials/mvc-4/getting-started-with-aspnet-mvc4/adding-a-controller

Categories

Resources