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')
Related
var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '#Url.Action("gettestjsn","Cart")',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(jso),
success: function (data) {
alert(data.namep);
},
error: function () { alert("err"); }
});
this code always go to error function and i does not fire my mvc action,aslo i have a prop class which does match to this json obj. why is that i m new to json and jquery ajax please help
this is my action
public ActionResult gettestjsn(jso jso)
{
//do some here
return View();
}
Remove contentType from the ajax attributes and add
dataType: 'json',
This will work if the url is correct
this is how your code should look like
var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '#Url.Action("gettestjsn","Cart")',
data: jso,
success: function (data) {
alert(data.namep);
},
error: function () { alert("err"); }
});
Also i would refrain from using alerts. Either use console.log or debug using the inspector in your browser (comes inbuilt with chrome) to see what your data from the server looks like.
Try like this,
var jso = { "namep": "a", "age": "10" };
$.ajax({
type: 'POST',
url: '/Cart/gettestjsn',
contentType: 'application/json; charset=utf-8',
data: jso,
success: function (data) {
alert(data.namep);
},
error: function (jqxhr, status, error) { alert("err:" + status + ':' + error); }
});
and your action should be,
[HttpPost]
public ActionResult gettestjsn(jso jso)
{
//do some here
return View();
}
Hope it helps.
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.
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.
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?
I have an ajax post and in the controller I return nothing. In case there is a failure will the error message displayed with the follwoing code?
[AcceptVerbs(HttpVerbs.Post)]
public void Edit(Model model)
{
model.Save();
}
$.ajax({
type: "POST",
url: '<%=Url.Action("Edit","test") %>',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function() {
},
error: function(request, status, error) {
alert("Error: " & request.responseText);
}
});
I would recommend you returning an empty result:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Model model)
{
model.Save();
return new EmptyResult();
}
also no need to specify data type:
$.ajax({
type: "POST",
url: '<%=Url.Action("Edit","test") %>',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: function() {
},
error: function(request, status, error) {
alert("Error");
}
});
In case the server returns a status code different than 200 the error callback will be called.