How to send javascript dictionary to controller method in MVC4 - c#

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>

Related

how to fix this my following code is not working

I am trying to post a data and trying to return from controller to back again and show it to alert box but dont know why this is not working
here is the controller code
[HttpPost]
public ActionResult getRequirmentsByProject(string projectname)
{
return Json(projectname, JsonRequestBehavior.AllowGet);
}
and here is my front end code
<input id="projName" type="text" name="Name" required="" value="javascript">
and this is my script code
var projectname = document.getElementById('projName').value;
$.ajax({
url: '/Worksheet/getRequirmentsByProject',
type: 'post',
data: { projectname },
contentType: 'application/json; charset=utf-8',
success: function (html) {
alert(html);
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
In your case, I am giving you a simple example on how you can POST your form variables to your controller using AJAX:
<script type="text/javascript">
var projectname = document.getElementById('projName').value;
var json = {
projectname: projectname
};
$.ajax({
url: '#Url.Action("getRequirmentsByProject", "Worksheet")',
type: 'post',
dataType: "json",
data: { "json": JSON.stringify(json)},
success: function (data) {
alert(data);
},
error: function (error) {
$(that).remove();
DisplayError(error.statusText);
}
});
</script>
And in your controller, you can get this value as:
using System.Web.Script.Serialization;
[HttpPost]
public ActionResult getRequirmentsByProject(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
string projectname= jsondata["projectname"];
return Json(projectname);
}
its httpget and writing with a wrong way
[HttpGet]
public ActionResult getRequirmentsByProject(string projectname)
{
return Json(projectname, JsonRequestBehavior.AllowGet);
}
this is the right way thankyou for pointing out

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);
}
});

pass value to controller by using ajax

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'
}
});
}

A Class with 2 list to MVC 4 Controler with ajax

i've tried to send a class with two list with ajax to an mvc controler.
MVC Controler :
[HttpPost]
public JsonResult AfficherDetailsFacture(AfficheDetails afficheDetailsFacture)
{
// do some stuff
}
C# Class for the controler argument:
[Serializable]
public class AfficheDetails
{
public List<long> firstList{ get; set; }
public List<long> secondList{ get; set; }
public string numFacture{ get; set; }
}
JS :
var AfficheDetails = {
firstList: [31025,6954],
secondList: [31542,31211,23214,23211],
numFacture: "Facture 001"
};
$.ajax({
type: "POST",
async: false,
url: urls.urlAfficherDetailsFacture,
contentType: 'application/json',
data: JSON.stringify(AfficheDetails),
success: function (oResultat) {
//
}
This is NOT working properly.
If firstlist has less element than secondList, then firstList is null in the MVC controller.
i've been working several hours to discover this "rule". If firstList has more element or the same ammount, it is working !
Is it a MVC Binding bug ?
You can also use on Controller
public JsonResult AfficherDetailsFacture(string jsonData)
{
var jss = new JavaScriptSerializer();
var data = jss.Deserialize<AfficheDetails>(jsonData);
// do some stuff
}
where data now contains all the values of the class AfficheDetails
and on Jquery
edit the line
$.ajax({
type: "POST",
async: false,
url: urls.urlAfficherDetailsFacture,
// contentType: 'application/json', comment the type
data: { jsonData : JSON.stringify(AfficheDetails) },
success: function (oResultat) {
//
}

In ASP.NET MVC3,can I get a JsonResult in View?

Suppose I have a Action which return a JsonResult. Like below code:
public ActionResult testAction()
{
return Json(new { name="mike",age="20"});
}
It json an anonymous object and return it. Then I want to write below code in View (.cshtml) file with razor engine.
#{
JsonResult m = ///some method can help me get the JsonResult
//Then I can print the value of m
#m.Data.ToString()
}
How to do it?
why do you use json result in view? You can:
public ActionResult testAction()
{
return View(new Model{ name="mike",age="20"});
}
In your View, you can call your testAction method via an Ajax call, then access to your returned object. But as far as I know, you must return a model.
Create a Model
public class YourModel
{
public string Name { get; set; }
public int Age { get; set; }
}
A Controller :
public ActionResult testAction(string name, int age)
{
YourModel ym = new YourModel();
ym.Name = name;
ym.Age = age;
return Json(ym, JsonRequestBehavior.AllowGet);
}
Your View :
var name = "Mike";
var age = "20";
$.ajax({
url : "#Url.Action("testAction", "YourController")",
contentType : "application/json; charset=utf-8",
dataType : "json",
type : "POST",
data : JSON.stringify({name: name, age: age})
}).done(function (data) {
alert(data); // Do what you want with your object, like data.Name
})
This is a dummy example because you pass parameter from the view to the controller, then send them back to the view, but I think this sample can help you to better understand how to play with Ajax call in ASP.NET MVC3. Ajax call is asynchronous, but thank to deferred .done, you wait for the end of the server call to ensure your data object is filled
You have to use ajax to read.
$.ajax({
url: "/YourController/testAction/",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: json,
type: 'POST',
success: function (data) {
setTimeout(function () {
//find your html element and show.
$("#ShowSomewhere").val(data.name);
}, 500);
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
try use Html.Action("actionName");
this return a string

Categories

Resources