AJAX POST to MVC Controller showing 302 error - asp.net-mvc

I want to do AJAX POST in my MVC View. I've written the following:
Script Code in View
$('#media-search').click(function () {
var data = { key: $('#search-query').val() };
$.ajax({
type: 'POST',
url: '/Builder/Search',
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('.builder').empty();
alert("Key Passed Successfully!!!");
}
});
});
Controller Code
[HttpPost]
public ActionResult Search(string key)
{
return RedirectToAction("Simple", new { key=key });
}
But on AJAX POST I am getting the 302 found Error

The '302' response code is a redirect. Your controller action explicitly returns a RedirectToAction, which simply returns a 302. Since this redirect instruction is consumed by your AJAX call and not directly by your browser, if you want your browser to be redirected, you will need to do the following:
$.ajax({
type: 'POST',
url: '/Builder/Search',
data: JSON.stringify(data),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.redirect) {
window.location.href = data.redirect;
}
$('.builder').empty();
alert("Key Passed Successfully!!!");
}
});
If not, you'll need to return something more meaningful than a redirect instruction from your controller.

Related

Why i can not send parameter to controller with ajax?

I write this ajax in view page in asp.net mvc:
<script type="text/javascript">
$(document).ready(function () {
$("#Shareitem").click(function (e) {
var serviceURL = '/Register/FirstAjax';
$.ajax({
type: "POST",
url: serviceURL,
data: '123',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
alert(data);
}
function errorFunc() {
alert('error');
}
});
});
</script>
and this is my action method in controller:
[HttpPost]
public ActionResult FirstAjax(string value)
{
string test = value.Trim();
return Json("PROF.VALI", JsonRequestBehavior.AllowGet);
}
but in this line:
string test = value.Trim();
get this error:
An exception of type 'System.NullReferenceException' occurred in UserRegister.dll but was not handled in user code
How can i solve that?thanks.
You need to send the data in a format that matches the name of the parameter of the method your posting to. Change the ajax data option to
data: JSON.stringify({ value: '123' }),
Alternatively, you can just use
data: { value: '123' },
and remove contentType: "application/json; charset=utf-8", option so it uses the default ('application/x-www-form-urlencoded; charset=UTF-8')

How to send JSON to MVC API (using Ajax Post)

I am trying to post some data using Ajax, but it is not getting through when using content type of application/json (HTTP/1.1 406 Not Acceptable), however if I change the content type to 'application/x-www-form-urlencoded' then it does work.
Any ideas?
Ajax code extract:
$.ajax({
type: "POST",
data: {"hello":"test"},
url: "http://workingUrl/controller",
contentType : 'application/json',
cache: false,
dataType: "json",
.....
Web API 2:
public IHttpActionResult Post(testModel hello)
{
/// do something here
}
Model:
public class testModel
{
public string hello {get;set;}
public testModel()
{ }
}
Fiddler:
HTTP/1.1 406 Not Acceptable (In the IDE, I have a breakpoint in the Post method which is not hit).
I have tried adding a formatter to WebAPi.config, but no luck
config.Formatters.Add(new JsonMediaTypeFormatter());
Try with this JSON.stringify(TestData) as shown below -
var TestData = {
"hello": "test"
};
$.ajax({
type: "POST",
url: "/api/values",
data: JSON.stringify(TestData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
console.log(data);
console.log(status);
console.log(jqXHR);
alert("success..." + data);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
Output -
I've never specified contentType when I've done this and it's always works. However, if it works when you use 'application/x-www-form-urlencoded' then what's the problem?
I do see a couple thing off in your ajax. I would do this
$.ajax({
type: "POST",
data: {hello:"test"},
url: "http://workingUrl/controller/Post",
cache: false)}
For data, maybe quotes around the variable name will work but I've never had them there.
Next, the url in the ajax call doesn't have the name of your controller action. That needs to be in there.

Making AJAX call to MVC API

I am trying to make an API call with ajax:
svc.authenticateAdmin = function (id, code) {
$.ajax({
url: 'api/event/authenticate',
data: { 'id': id, 'code': code },
datatype: 'json',
contentType: 'application/json',
type: 'GET',
success: function (data) {
App.eventBus.publish('authenticationComplete', data);
}
});
};
The method in the API Controller:
[ActionName("All")]
public bool Authenticate(int id, string code)
{
var repo = new MongoRepository<Event>(_connectionString);
var entry = repo.FirstOrDefault(e => e.Id == id);
return entry.AdminPassword == code;
}
But I am getting a 404 error: urlstuff/api/event/authenticate?id=123&code=abc 404 (Not Found)
I have copied the implementation from a number of known working calls (that I did not write). That look like:
svc.getEventFromCode = function (code) {
$.ajax({
url: '/api/event/',
data: { 'code': code },
dataType: 'json',
type: 'GET',
success: function (data) {
App.eventBus.publish('loadedEvent', data);
App.eventBus.publish('errorEventCodeExists');
},
error: function () {
App.eventBus.publish('eventNotFound', code);
}
});
};
and
svc.getEventPage = function (pageNumber) {
$.ajax({
url: '/api/event/page/',
data: { 'pageNumber': pageNumber },
dataType: "json",
contentType: "application/json",
type: 'GET',
success: function (data) {
App.eventBus.publish('loadedNextEventsPage', data);
}
});
};
But neither has to pass in 2 parameters to the API. I'm guessing it's something really minor :/
Your action name is called "Authenticate", but you have included the following which will rename the action:
[ActionName("All")]
This makes the URL
/api/event/all
The problem lies in your url.
Apparently, ajax interpret / at the start of the url to be root
When the application is deployed on serverserver, its URL is something like http://localhost:8080/AppName/
with api/event/page/, ajax resolve the URL to http://localhost:8080/AppName/api/event/page/ or an url relative to your current directory.
However, with /api/event/page/, the URL is resolved to http://localhost:8080/api/event/page/
Hope it helped.

Ajax json post is not working

I need to pass a json data to the controller. hence i have created a ajax post. But it is not calling the action method.
function DeleteRow(postData) {
$.ajax({
url: '#Url.Action("DeleteGridRow","Project")',
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
async: false,
data: JSON.stringify(postData),
success: function (data) {
}
});
}
My Actionmethod
[HttpPost]
public JsonResult DeleteGridRow(string postData)
{
return Json(null);
}
Please help
If you have separated your javascript file from your cshtml or vbhtml page, then this is not going to work. Your URL would be interpreted wrongly. You should pass URL where you are submitting to your function DeleteRow. Something like this:
$("#myForm").submit(function() {
var url = $(this).attr("action");
var data = Use your method to collect data or $(this).serialize();
DeleteRow(url, data);
});
function DeleteRow(url, postData) {
$.ajax({
url: url,
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
async: false,
data: JSON.stringify(postData),
success: function (data) {
}
});
Something like this should work.

Return a PartialView from $.Ajax Post

I have the following code;
$.ajax({
url: "/Home/jQueryAddComment",
type: "POST",
dataType: "json",
data: json,
contentType: 'application/json; charset=utf-8',
success: function(data){
//var message = data.Message;
alert(data);
$('.CommentSection').html(data);
}
And in my controller;
[ValidateInput(false)]
public ActionResult jQueryAddComment(Comment comment)
{
CommentSection commentSection = new CommentSection();
//ya da - ya da
// fill the commentsection object with data
//then
return PartialView("CommentSection", commentSection);
}
However, when I get back to the page the success alert doesn't happen. Can anyone see the flaw in this logic?
Your expecting JSON in the .Ajax POST, but in the ActionMethod your returning a PartialView?
Try:
$.ajax({
url: "/Home/jQueryAddComment",
type: "POST",
dataType: "html",
data: json,
success: function(data){
//var message = data.Message;
alert(data);
$('.CommentSection').html(data);
}
}
Unless it was copied over wrong it appears you are missing some closing tokens.
$.ajax({
url: "/Home/jQueryAddComment",
type: "POST",
dataType: "json",
data: json,
contentType: 'application/json; charset=utf-8',
success: function(data){
//var message = data.Message;
alert(data);
$('.CommentSection').html(data);
} //<-- added close for anonymous function
}); //<--added close/semicolon for ajax function
Also, you are POSTing but it your action doesn't appear to have the [Post] attribute. When you run this in the debugger does a breakpoint on your action get hit?

Resources