how to get the result from controller in ajax json - asp.net-mvc-3

Isend the some aruguments to controller using ajax but it does not return the value.
My concept : selected #html.dropdownlist value i send to the controller , using this value thats perfrom the get the valus for bind the property to another dropdownlist using mvc3
IGot this answer : verfif given link
verfif given link

you are passing type option in ajax twice and the url is not formatted properly
function onChange(bookid) {
$.ajax({
type: "GET",
url: '#Url.Action("books","subject")',
data : { bookid: bookid},
dataType: "json",
success: function (result) {
alert('success');
//do whatever you want
},
error: function(result){
}
});
};
You are passing dataType as json. So, if you want to hit the success result for $.ajax, you need to return Json from your action result instead of returning as View.
When you return as View it gives error always.
public ActionResult books(string bookid)
{
var books= service.books(projectId);
// books are stored in list format
return Json(books);
}
Hope it helps you.

Related

Sending data to MVC Controller with AJAX

I am trying to send data with AJAX to MVC Controller method, but I don't know what am I doing wrong.
Here is the AJAX call
$.ajax({
type: 'POST',
url: invokingControllerActionUrl,
data: "it is just a simple string",
success: function (data) {
window.location.href = link;
}
});
And here is the controller method. It is invoked, but the parameter is always null.
public IActionResult OnPostTest([FromBody] string stringValue)
{
// stringValue is always null :(
}
Change you ajax call to this
$.ajax({
type: 'POST',
url: invokingControllerActionUrl, // Confirm the Path in this variable Otherwise use #Url.Action("OnPostTest", "InvokingController")
data: {stringValue: "it is just a simple string"},
success: function (data) {
window.location.href = link;
}
});
And remove the [FromBody]. ALso its better to define type post. Not necessary though
[HttpPost]
public IActionResult OnPostTest( string stringValue)
{
// stringValue is always null :(
}
Depending on what Content-Type you are sending from JS, you might need to encode your string properly, as a form-value
...
data: 'stringValue="it is just a simple string"',
...
or e.g. JSON:
...
data: '{stringValue: "it is just a simple string"}',
...
See also this discussion
I haven't found an easy way to pass a string of unformatted data via parameter, unfortunately. According to this answer, you can do the following:
public IActionResult OnPostTest()
{
Stream req = Request.Body;
req.Seek(0, System.IO.SeekOrigin.Begin);
string stringValue = new StreamReader(req).ReadToEnd();
...
// process your stringValue here
...
}

Retrieve post value in the controller sent by ajax call

I am unable to retrieve value sent as a post through ajax call in cake php controller file
$.ajax({
type: "POST",
url: "share",
data: country,
dataType: "json",
success: function (response) {
if (response.success) {
// Success!
} else {
console.log(response.data, response.code);
}
}
});
I have tried with the below ways of retrieving the data sent in the above code through POST. But none of them worked.
$this->params
$this->data
$_POST[]
$this->request
The url points to the function in the controller page.
Please can any of you let me know how the value can be retrieved.
When submitting data via ajax and you want cake to pick it up in the usual way just use $('whatever').serialize().
if you don't have an actual form to serialize you can fake it by submitting the data as follows:
$.ajax({
...
data: {
data: country
},
...
});
Note how cake generates fields like data[Model][field]. you don't need the Model part but the data part is important.

How to filter occupation as you type in MVC3

I have a list of 2500 occupations held in our db. On our site we ask for you to enter your occupation and I would like it to filter the results as they type; like Play.com's search. Is there a way to do this in MVC3?
Appreciate any help.
You can do this using a autocomplete javascript.
For example:
http://www.pnpguidance.net/post/jQueryAutoCompleteASPNETMVCFramework.aspx
You can grab your data using jQuery Ajax.
I would create an action method that would return JSON:
[HttpGet()]
public JsonResult Occupations(String searchCriteria)
{
String[] occupations = new String[] { "Lawyer", "Carpenter" };
return Json(occupations.Where(s => s.Contains(searchCriteria))
.ToList(), JsonRequestBehavior.AllowGet);
}
If you run a GET request on this link: /Occupations?searchCriteria=Carpenter you'll receive ["Carpenter"] in a response.
I would make a jQuery ajax call to this action method. On success, I would take a reponse and generate an output such as list of li elements to select from.
Example of an ajax json get request is below:
$.ajax({
type: 'json',
url: '/Occupations',
type: 'GET',
cache: false,
data: { searchCriteria: searchCriteria},
error: function () {
},
success: function (result) {
alert(result);
}
});
This is from a notepad, so there might be some minor syntax errors.

Render Partial View using Jquery Ajax with variable data

I have already read this post, but I am not sure know to make it work taking data from the user. Here is the ajax jquery I am using. I know (or at least think) that this cant render a partial. But it works all the way until the render fails. I thought it may be helpful to have.
$.ajax(
{
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: "{'test':" + "'" + dateText + "'}",
dataType: 'json',
url: 'Site/Grab/',
success: function (result) {
alert('Success');
},
error: function (error) {
alert('Fail');
}
});
Here is my controller
[HttpPost]
public ActionResult Grab(string test)
{
DateTime lineDate= Convert.ToDateTime(test);
List<Info> myInfo= GameCache.Data(lineDate);
return PartialView("_PartialView", myInfo);
}
Okay, couple of things to try:
1) dataType is the expected result of the ajax call. In your case, your sending JSON, but receiving HTML. The content-type parameter specifies the request, which you have (and what you have is correct). So the data type should be:
dataType: 'html',
2) You need to serialize the JSON. Try grabbing the lightweight JSON library and stringify'ing:
var test = { test: 'testvalue' };
$.ajax {
...
data: JSON.stringify(test),
...
});
Much easier than trying to coerce a JSON string with quoatations. Create a regular JS variable, then stringify it.
The rest of your code looks fine.
If it's a problem with the HTML/markup of the partial view itself, run in debug mode and Visual Studio should stop on the line in the markup that is causing the problem.
Bonus Hint: ASP.NET MVC 3 includes built-in JSON model binding. So you can create a basic POCO that matches the fields of your JSON object, then accept it as a strongly-typed object in the action method:
[HttpPost]
public ActionResult Grab(MyJsonObject obj)
{
DateTime lineDate= Convert.ToDateTime(obj.test);
List<Info> myInfo= GameCache.Data(lineDate);
return PartialView("_PartialView", myInfo);
}
Since your only sending one parameter, it's overkill - but if you have more than 2 then it's worthwhile using a JSON POCO.
Change your controller code to:
public ActionResult Grab(string test) {
DateTime lineDate= Convert.ToDateTime(test);
List<Info> myInfo= GameCache.Data(lineDate);
return Json(new { data = this.RenderPartialViewToString("_PartialView", myInfo) });
}

DOJO xhrGet how to use returned json object?

How can I access the data returned from the xhrGet outside of the get itself? Firebug shows that the "json" object has an array called results, which stores the json Object from the response, but when I try to access it it is null. So: how do I access the received data on the last code line?
var json = dojo.xhrGet({
url :'/disease_web/graphMlDownload/getEdgeInformation/', handleAs:"json",content : { edgeid : edgeId, graphname:this._canvas.path},
load:function(response){
return response;
}
});
console.log(json.ioArgs);
console.log(json.results);
By default dojo.xhrGet is called asynchronously, so console.log(json.results) is null because it's run just after dojo.xhrGet, but before response comes from server.
var xhrGet = dojo.xhrGet({
url: "/some_rul",
handleAs: "json",
handle: function(response) {
console.info(2,'response',response);
console.info(3,'xhrGet.results[0]',xhrGet.results[0]);
}
});
console.info(1,xhrGet.hasOwnProperty('results'));
The result is:
1 false
2 response - ['some data from server']
3 xhrGet.results[0] - same data as in 'response' accessed via xhrGet
The simplest way to access your retrieved JSON data is to assign it to a document-level variable within the xhrGet load function:
var fetchedData = null;
function parseResponse() { /* do something meaningful */ }
dojo.xhrGet({
url: "{{dataUrl}}dojo/LICENSE",
handleAs: "json",
preventCache: true,
load: function(response){
// save for later
window.fetchedData = response;
// do whatever processing we want with the returned data
parseResponse();
},
error: function(error){
alert("Couldn't fetch your data: " + error);
}
});
Yeah, no. I've since learned a much better way, and forgot to come back and fix this answer, so it deserves the downvotes it's accrued.
The proper way to deal with data fetched from dojo.xhrGet, jQuery.ajax, or any other asynchronous data fetch is to write a function to process its results, and pass it to xhrGet as the load argument, like so:
var request = dojo.xhrGet({ url :'/disease_web/graphMlDownload/getEdgeInformation/',
handleAs: "json",
content : {edgeid : edgeId, graphname:this._canvas.path},
load: doSomethingWithMyEdges
});
function doSomethingWithMyEdges(json_results) {
console.log(json_results);
}

Resources