asp.net mvc and jquery - asp.net-mvc

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

Related

Ajax Request issue with ASP.NET MVC 4 Area

Today i discovered something weird, i have regular asp.net mvc 4 project with no such ajax (just post, get). so today i need ajax request, i did an ajax action with jquery in controller and it didn't work out. Here is my code
Areas/Admin/Controllers/BannersController
public JsonResult SaveOrder(string model)
{
bool result = false;
if (!string.IsNullOrEmpty(model))
{
var list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<int>>(model);
result = repository.SaveOrder(list);
}
return Json(result, JsonRequestBehavior.AllowGet);
}
View side (Its in area too)
$(document).ready(function () {
$("#saveOrder").click(function () {
var data = JSON.stringify($("#list_banners").nestable('serialize'));
$.ajax({
url: '#Url.Action("SaveOrder", "Banners", new { area = "Admin" })',
data: { model: data },
success: function (result) {
if (result) {
toastr.success('Kaydedildi.');
}
else {
toastr.error('kaydedilemedi.');
}
},
error: function (e) {
console.log(e);
}
});
});
});
i've already tried everything i know, which is $.post, $.get, ajax options, trying request from out of area etc.. just request can't reach action
and here is the errors ,
http://prntscr.com/297nye
error object
http://prntscr.com/297o3x
Try by specifying the data format (json) you wand to post to server like and Also change the way you pass data object in JSON like this :
var data = $("#list_banners").nestable('serialize');
$.ajax({
url: '#Url.Action("SaveOrder", "Banners", new { area = "Admin" })',
data: JSON.stringify({ model: data }),
dataType: 'json',
contentType: "application/json",
...
I had same issue, but after spending too much time, got solution for that. If your request is going to your specified controller, then check your response. There must be some problem in your response. In my case, response was not properly converted to JSON, then i tried with passing some values of response object from controller using select function, and got what i needed.

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.

How to return a View to a New/Separate browser window using an AJAX call

jQuery:
$.ajax({
type: 'POST',
url: redirectToANewWindow,
dataType: 'html',
data: { filterValue: searchValue },
success: function (result) {
$('form').html(result);
}
});
Controller:
[HttpPost]
public ActionResult InitializeEditView(string filterValue)
{
//some code
return PartialView("PartialForm", model);
}
This works fine. It returns the updated view and paste it on the current page. But what I want to acheive is after it passes from the controller, the result should be rendered on a new/separate browser window. How do I do that?
Thanks in advance!
If I understand your question, you would like this form to create a new window? Get rid of the jquery and just add this attribute to the form's html:
target="_blank"
as in
<form action="/yourcontroller" method="post" target="_blank">
...
</form>
EDIT:
You could feasibly do it like this:
$.ajax({
type: 'POST',
url: redirectToANewWindow,
dataType: 'html',
data: { filterValue: searchValue },
success: function (result) {
var w = window.open();
$(w.document.body).html(result);
}
});
Currently you have decided to make an AJAX call and place the recived data in the form element by writing:
$('form').html(result);
in your AJAX success callback.
Don't use AJAX.. just open a new window with the required URL:
window.open('http:// ... my web?param1=0&param2=1')
This would require you to change the controller action to receive GET requests
and to return a full view.
[HttpGet]
public ActionResult InitializeEditView(string filterValue)
{
//some code
return View("PartialForm", model);
}
You don't need to use ajax here.You need to open a new window so you need simply trigger this
window.open('/ActionName/InitializeEditView??filterValue='+searchValue)
That's not an AJAX post, if you want the whole browser window to update.
It's a standard HTML <FORM> post, change it to that.
[Edited]
OK, you want to open a separate window. Do that as a GET with window.open(), or a POST via jQuery & then put the HTML into it on success.

Returning JSON from action method

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>

How to send a model in jQuery $.ajax() post request to MVC controller method

In doing an auto-refresh using the following code, I assumed that when I do a post, the model will automatically sent to the controller:
$.ajax({
url: '<%=Url.Action("ModelPage")%>',
type: "POST",
//data: ??????
success: function(result) {
$("div#updatePane").html(result);
},
complete: function() {
$('form').onsubmit({ preventDefault: function() { } });
}
});
Every time there is a post, I need to increment the value attribute in the model:
public ActionResult Modelpage(MyModel model)
{
model.value = model.value + 1;
return PartialView("ModelPartialView", this.ViewData);
}
But the model is not passed to the controller when the page is posted with jQuery AJAX request. How can I send the model in the AJAX request?
The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.
As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.
For example, the Javascript:
var values =
{
"Name": "Chris",
"Color": "Green"
}
$.post("#Url.Action("Update")",values,function(data)
{
// do stuff;
});
The model:
public class UserModel
{
public string Name { get;set; }
public string Color { get;set; }
public IEnumerable<string> Contacts { get;set; }
}
The controller:
public ActionResult Update(UserModel model)
{
// do something with the model
return Json(new { success = true });
}
If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.
In our app, we do this with an extension method:
public static class JsonExtensions
{
public static string ToJson(this Object obj)
{
return new JavaScriptSerializer().Serialize(obj);
}
}
On the view, we use it to render the model:
<script type="javascript">
var model = <%= Model.ToJson() %>
</script>
You can then pass the model variable into your $.ajax call.
I have an MVC page that submits JSON of selected values from a group of radio buttons.
I use:
var dataArray = $.makeArray($("input[type=radio]").serializeArray());
To make an array of their names and values. Then I convert it to JSON with:
var json = $.toJSON(dataArray)
and then post it with jQuery's ajax() to the MVC controller
$.ajax({
url: "/Rounding.aspx/Round/" + $("#OfferId").val(),
type: 'POST',
dataType: 'html',
data: json,
contentType: 'application/json; charset=utf-8',
beforeSend: doSubmitBeforeSend,
complete: doSubmitComplete,
success: doSubmitSuccess});
Which sends the data across as native JSON data.
You can then capture the response stream and de-serialize it into the native C#/VB.net object and manipulate it in your controller.
To automate this process in a lovely, low maintenance way, I advise reading this entry that spells out most of native, automatic JSON de-serialization quite well.
Match your JSON object to match your model and the linked process below should automatically deserialize the data into your controller. It's works wonderfully for me.
Article on MVC JSON deserialization
This can be done by building a javascript object to match your mvc model. The names of the javascript properties have to match exactly to the mvc model or else the autobind won't happen on the post. Once you have your model on the server side you can then manipulate it and store the data to the database.
I am achieving this either by a double click event on a grid row or click event on a button of some sort.
#model TestProject.Models.TestModel
<script>
function testButton_Click(){
var javaModel ={
ModelId: '#Model.TestId',
CreatedDate: '#Model.CreatedDate.ToShortDateString()',
TestDescription: '#Model.TestDescription',
//Here I am using a Kendo editor and I want to bind the text value to my javascript
//object. This may be different for you depending on what controls you use.
TestStatus: ($('#StatusTextBox'))[0].value,
TestType: '#Model.TestType'
}
//Now I did for some reason have some trouble passing the ENUM id of a Kendo ComboBox
//selected value. This puzzled me due to the conversion to Json object in the Ajax call.
//By parsing the Type to an int this worked.
javaModel.TestType = parseInt(javaModel.TestType);
$.ajax({
//This is where you want to post to.
url:'#Url.Action("TestModelUpdate","TestController")',
async:true,
type:"POST",
contentType: 'application/json',
dataType:"json",
data: JSON.stringify(javaModel)
});
}
</script>
//This is your controller action on the server, and it will autobind your values
//to the newTestModel on post.
[HttpPost]
public ActionResult TestModelUpdate(TestModel newTestModel)
{
TestModel.UpdateTestModel(newTestModel);
return //do some return action;
}
I think you need to explicitly pass the data attribute. One way to do this is to use the
data = $('#your-form-id').serialize();
This post may be helpful.
Post with jquery and ajax
Have a look at the doc here..
Ajax serialize
you can create a variable and send to ajax.
var m = { "Value": #Model.Value }
$.ajax({
url: '<%=Url.Action("ModelPage")%>',
type: "POST",
data: m,
success: function(result) {
$("div#updatePane").html(result);
},
complete: function() {
$('form').onsubmit({ preventDefault: function() { } });
}
});
All of model's field must bo ceated in m.
In ajax call mention-
data:MakeModel(),
use the below function to bind data to model
function MakeModel() {
var MyModel = {};
MyModel.value = $('#input element id').val() or your value;
return JSON.stringify(MyModel);
}
Attach [HttpPost] attribute to your controller action
on POST this data will get available

Resources