Return a PartialView from $.Ajax Post - asp.net-mvc

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?

Related

#Url.Action does not reach my controller

I have created a class for my Ajax call, like this:
function sendAjaxCustom(DataType, Type, Url, Ctype, Data) {
debugger;
$.ajax({
dataType: DataType,
type: Type,
url: Url,
contentType: Ctype,
data: Data,
success: function (result) {
return result;
}
})
}
In my view I am passing parameters like:
var result = sendAjaxCustom("json", "POST", '#Url.Action("ErrorStat","Ranking")', "application/json; charset=utf-8", JSON.stringify({ "regionalManager": tmpString }));
The problem is when pass #Url.Action("ErrorStat","Ranking"), it does not work, that means will not reach my controller to get data.

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.

AJAX POST to MVC Controller showing 302 error

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.

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.

Resources