Returning JSON from action method - asp.net-mvc

I have this action methid. It will return some JSON.
public JsonResult Get()
{
...
return new JsonResult { Data = data }, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
Then I have in my view a script tag pointing to the Get action method.
<script type="text/javascript" src="#Url.Content("~/resource/get")"></script>
The problem is I can't access the JSON data in JS code. It seems like the JSON needs to be executed somehow. Any suggestion ?

You can just call the action in jQuery and then process the Json directly:
$.ajax({
dataType: "json",
url: "/resource/get",
success: function(data){
var obj = JSON.parse(data);
}
});
Or a shorter version:
$.getJSON('/resource/get', function(data) {
var obj = data;
});

If you want the JSON available ASAP, without an extra request, include it in the initial page load:
<script type="text/javascript">
var myJson = #Html.Action("Get");
</script>
Now you can just access the myJson variable in your script to access your data.

If you want it to be dumped into your HTML at the time the page is built on the server, you can add it to your view model, then render it directly on the page. Here's a pseudo-code example:
<script type="javascript">
var obj= JSON.parse('#Model.PropertyContainingJson');
</script>

Related

How to get value of form filed card_number to pass to the controller?

How would I get the value of card_number to pass to the controller?
Every time I submit the form I get NULL in the form variable
View:
#Html.EditorFor(model => model.card_number, new { htmlAttributes = new { #id = "card_number" } })
<script>
var frm = $('#formFilter');
function OnFormSubmit() {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: function (frm) {
frm.card_number = $('#card_number').val();
},
success: function (data) {
$("#dataResult").html(data);
$('#dataTable').DataTable({
"dom": 'lifrtp'
});
}
});
}
</script>
controller:
private List<testtest> GetListChanges(Report changeControl)
{
...logic here....
return returnListhere;
}
The data property of the $.ajax method options should be an object or string which represents your data. With your current code you are setting a function to that.
var d = {
card_number: "1234",
someOtherPropertyNameOfReport: "Hello"
};
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: JSON.stringify(d),
contentType:"application/json",
success: function (data) {
console.log(data);
}
});
Now jquery will send the request with Content-Type request header value set to application/json and request data (the stringified version of your JavaScript object) in the request body and model binder will be able to properly read and map it to your view model, assuming the structure of the view model matches with your JavaScript object structure.
As suggested in the comment, try to use serialize() method. It is simply and you do not need to manually build the object.
Also your controller action method should be public

How to call local MVC 4 function inside ajax call

In my SPA website i need to send antiforrgery token over to server by ajax. I use this article method:
http://www.asp.net/web-api/overview/security/preventing-cross-site-request-forgery-%28csrf%29-attacks
So in my layout.cshtml i have local function :
<script>
#functions{
public string TokenHeaderValue()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + ":" + formToken;
}
}
</script>
and i have separate js file named register.js where i call this function inside ajax:
$.ajax({
url: 'User/JsonRegister',
type: "POST",
data: d,
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
},
success: function (result) {
},
error: function (result) {
}
});
the problem is that i never #TokenHeaderValue() is never called and i m keep getting this error:
The required anti-forgery form field "__RequestVerificationToken" is not present.
How do i solve this problem?
The problem is using server side helper function in the separate js file. If you need to have ajax call in the separate js file, set #TokenHeaderValue() value to a hidden field and read the value of hidden field in the js file.
i add token to my data this way: which solves problem
AddAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val();
return data;
};
Pass data in JSON format
$.ajax({
type:"POST",
datatype:"JSON",
data:{d:d}, // Remaining code is same
});
And use [HttpPost] before method signature in controller because it a Post request.

mvc json request life cycle

I'm pretty new to asp.net and MVC.
I was trying to use json request and populate some text boxes.
but I noticed when I'm using json, I can not access values of the other text boxes in my view.
for example
string s2 = Request.Form["selectedTestCategory"];
would generate s2 = null, when I debug.
but if I put a submit button on the page, the value is not null. (And so far I know I can only pass one parameter to my JSON method in controller)
My question is what happens when I start a json request? and why I can not get a value from Request.Form[...]
Thanks,
Update:
This is my json
<script>
$(document).ready(function() {
$('select#testStationUniqueId').change(function() {
var testStation = $(this).val();
$.ajaxSetup({ cache: false });
$.ajax({
url: "TestInput/getTestStationInformation/" + testStation,
type: 'post',
success: function(data) {
$('#driveDetailDiv').empty();
for (var i = 0; i < data.length; i++) {
$.post('TestInput/Details/', { id: data[i] }, function(data2) {
$('#driveDetailDiv').append(data2);
});
}
}
});
});
});
And this is in my controller
public PartialViewResult Details(string id)
{
//DriveDetails t = new DriveDetails(id);
//return PartialView("DriveDetailsPartial", t);
test_instance_input_model ti = new test_instance_input_model();
string s2 = Request.Form["selectedTestCategory"];
repository.setTestInstanceAttributes(ti, id);
return PartialView("TestInstancePartial", ti);
}
the s2 is null in Details, but if I use a submit button, it will have the correct value.
so I'm trying to figure out why it is null when I send a json request.
In your JavaScript your not including any data in the jQuery ajax request (see jQuery ajax). Therefore jQuery isn't adding any request parameters. You need to include a data object which jQuery will turn into parameters i.e. the more properties in the data object the more parameters in the request.
$.ajax({
url: '',
data: { selectedTestCategory: 'category' },
dataType: 'post',
success: function() {}
});
Also, in your controller you can shortcut to the request parameter.
string s2 = Request["selectedTestCategory"];

asp.net mvc and jquery

In my MVC view (using VS 2012 RC), I'm attempting to use jQuery to parse XML data returned from my Controller. However, my focus is to make use of the jQuery $.ajax() function.
Problem is that ajax is NOT returning an XML Doc from my controller; it returns some formatted Html.
Example:
I can indeed return it directly to my view inside a , but I don't want that entire XML doc displayed that way. For example, get XML from the #Model object:
#model RazorMvc.Models.PortfolioResponse
#{
ViewBag.Title = "PortfolioList";
}
...
<div class="XmlResp">
<#Html.Raw(#Model.XmlPortfolioResponse.OuterXml.ToString())>
</div>
HOWEVER, I would much prefer to use $.ajax() to retrieve my XML Doc. The only problem is that the return value from my Controller code is NOT the XML; it's returning some formatted HTML text:
This is a test div !!!
What's getting displayed is some formatted HTML as follows:
Wow are we getting somewhere ?!!! My company SolutionsRegisterLog inHomeAboutContactPortfoliosPortfolioListPortfolio ListingThis is a test div !!!© 2012 - My ASP.NET MVC ApplicationFacebookTwitter
Here is the jQuery code. I would hope to get an XML doc in the DATA object:
<script type="text/javascript">
$.ajax({
url: "/Portfolios/PortfolioList",
type: "POST",
async: true,
success: function(data){
if (!data)
alert("No xml data returned.");
else{
var $xml = $(data);
var $title = $xml.find("portfolioSummary").text();
$('.xmlTest').text("Wow are we getting somewhere ?!!!");
$('.xmlTest').append($xml.text());
alert("success!");
}
},
error: function (error) {
alert("failed");
}
});
Some guidance and advice would be greatly appreciated.
Thanks,
Bob
You don't need a view. You could return the XML directly from your controller action:
[HttpPost]
public ActionResult PortfolioList()
{
string xml = ...
return Content(xml, "text/xml");
}
Now, since you have set the proper content type response header, jQuery will know how to parse it and in your success callback you will be able to directly work with this XML stream.
You probably need to specify the dataType as XML in your .ajax() setup as seen below
$.ajax({
url: "/Portfolios/PortfolioList",
type: "POST",
//add this line
dataType: "XML",
async: true,
success: function(data){
if (!data)
alert("No xml data returned.");
else{
var $xml = $(data);
var $title = $xml.find("portfolioSummary").text();
$('.xmlTest').text("Wow are we getting somewhere ?!!!");
$('.xmlTest').append($xml.text());
alert("success!");
}
},
error: function (error) {
alert("failed");
}
});
There are other options as well from the JQuery documentation on this function depending on your needs

Passing data from Controller to View using JSon object

I have the following to get the Json abject passed from the controller and populate the various textboxes in the view. However, nothing is happening even though controller is passing a valid Json object. What is wrong with this code???
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var url = '<%=Url.Action("DropDownChange") %>';
$("#vendorID").change(function() {
var selectedID = $(this).val();
if (selectedID != "New Vendor Id") {
//$.post('Url.Action("DropDownChange","Refunds")', function(result) {
$.post(url, { dropdownValue: selectedID }, function(result) {
alert(selectedID);
$("#name").val(result.Name);
$("#city").val(result.City);
$("#contact").val(result.Contact);
$("#address2").val(result.Address2);
$("#address1").val(result.Address1);
$("#state").val(result.State);
$("#zip").val(result.Zip);
});
}
});
});
This is the code in my controller;
public JsonResult DropDownChange(string dropdownValue)
// This action method gets called via an ajax request
{
if (dropdownValue != null && Request.IsAjaxRequest() == true)
{
paymentApplicationRefund =
cPaymentRepository.PayableEntity(dropdownValue);
paymentApplicationRefund.Address1.Trim();
paymentApplicationRefund.Address2.Trim();
paymentApplicationRefund.Name.Trim();
paymentApplicationRefund.City.Trim();
paymentApplicationRefund.Contact.Trim();
paymentApplicationRefund.State.Trim();
paymentApplicationRefund.Zip.Trim();
return Json(paymentApplicationRefund,"application/json");
}
else
{
return null;
}
}
You probably just need to tell it to expect JSON data back. By default it assumes it's HTML.
$.post(url, { dropdownValue: selectedID }, function(result) {
alert(selectedID);
$("#name").val(result.Name);
$("#city").val(result.City);
$("#contact").val(result.Contact);
$("#address2").val(result.Address2);
$("#address1").val(result.Address1);
$("#state").val(result.State);
$("#zip").val(result.Zip);
}, 'json');
I prefer sending Json to a ActionResult with my DTO as the parameter and use the JsonValueProviderFactory do the deserialization for me.
Sending JSON to an ASP.NET MVC Action Method Argument
Try this...
Add the ".change()" at the end of the function.
$(document).ready(function() {
var url = '<%=Url.Action("DropDownChange") %>';
$("#vendorID").change(function() {
.....
}).change();
});

Resources