how to send serialized form to webapi Method - ajax

im trying to send my from with ajax( $.post ) to a webApi . ajax request run succesfull but when i send data to method in web api form collection get null then my method return "false"
please help me
My WebApi Method
[System.Web.Http.HttpPost]
public string AddRecord([FromBody]FormCollection form)
{
try
{
PersonBLL personbll = new PersonBLL();
var person = new tbl_persons();
person.firstname = form["txt_namePartial"];
person.lastname = form["txt_lastnamePartial"];
person.age = byte.Parse(form["txt_agePartial"]);
var result = personbll.AddRecord(person);
return result;
}
catch (Exception)
{
return "false";
}
}
my Ajax function
function AddRecordWithFormCollection(url, callback) {
$.post("/api/Person/AddRecord",JSON.stringify(url) , function (data, status) {
if (status == "success") {
hidePreloader();
unloadDiv("div_operation");
BindTable();
//AddRowTable(data, obj.name, obj.lastname, obj.age);
return callback(data);
} else {
alert("Error in Method [AddRecord]");
hidePreloader();
}
});
}

I often use that :
var form = $("#body").find("form").serialize();
$.ajax({
type: 'POST'
url: "/api/Person/AddRecord",
data: form,
dataType: 'json',
success: function (data) {
// Do something
},
error: function (data) {
// Do something
}
});
Get a try because I never used the FormCollection object type but just a model class.

This should be:
url=$("#form").serialize();
function AddRecordWithFormCollection(url, callback) {
$.post("/api/Person/AddRecord",url , function (data, status) {
if (status == "success") {
hidePreloader();
unloadDiv("div_operation");
BindTable();
//AddRowTable(data, obj.name, obj.lastname, obj.age);
return callback(data);
} else {
alert("Error in Method [AddRecord]");
hidePreloader();
}
});
}

Related

Ajax post method returns undefined in .net mvc

I have this ajax post method in my code that returns undefined. I think its because I have not passed in any data, any help will be appreciated.
I have tried passing the url string using the #Url.Action Helper and passing data in as a parameter in the success parameter in the ajax method.
//jquery ajax post method
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action("Bookings/SaveBooking")',
data: data,
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
//controller action
[HttpPost]
public JsonResult SaveBooking(Booking b)
{
var status = false;
using (ApplicationDbContext db = new ApplicationDbContext())
{
if (b.ID > 0)
{
//update the event
var v = db.Bookings.Where(a => a.ID == a.ID);
if (v != null)
{
v.SingleOrDefault().Subject = b.Subject;
v.SingleOrDefault().StartDate = b.StartDate;
v.SingleOrDefault().EndDate = b.EndDate;
v.SingleOrDefault().Description = b.Description;
v.SingleOrDefault().IsFullDay = b.IsFullDay;
v.SingleOrDefault().ThemeColor = b.ThemeColor;
}
else
{
db.Bookings.Add(b);
}
db.SaveChanges();
status = true;
}
}
return new JsonResult { Data = new { status } };
}
Before the ajax call, you should collect the data in object like,
var requestData= {
ModelField1: 'pass the value here',
ModelField2: 'pass the value here')
};
Please note, I have only added two fields but as per your class declaration, you can include all your fields.
it should be like :
function SaveEvent(data) {
$.ajax({
type: "POST",
url: '#Url.Action(Bookings,SaveBooking)',
data: JSON.stringify(requestData),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.status) {
//Refresh the calender
FetchEventAndRenderCalendar();
$('#myModalSave').modal('hide');
}
},
error: function (error) {
alert('Failed' + error.val );
}
})
}
Try adding contentType:'Application/json', to your ajax and simply have:
return Json(status);
In your controller instead of JsonResult. As well as this, You will need to pass the data in the ajax code as a stringified Json such as:
data:JSON.stringify(data),
Also, is there nay reason in particular why it's a JsonResult method?

Routing through AJAX

I have an ajax request handling validation of form fields (login+signup+forget password). In its success scenario, I want it to route to another page, but when I use Redirect::route('name'); as return from controller, it completes the request with 200 and generates another GET request which just returns the html as response and does not route to other page.
AJAX
$('form[data-remote]').on('submit', function (e) {
var form = $(this);
var method = form.find('input[name="_method"]').val() || 'POST';
var url = form.prop('action');
$.ajax({
type: method,
url: url,
data: form.serialize(),
beforeSend: function () {
$('#ajax-loading').show();
$(".has-error").text("");
$('#login-error').addClass('display-hide');
$('#forget-user-error').addClass('display-hide');
}
})
.done(function (data) {
if (data.signup_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).removeClass('hidden');
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
else if (data.email_fail) {
$('#email_error').text('This Email already in use against an account.');
}
else if (data.company_fail) {
$('#email-error-popup').trigger('click');
}
else if (data.login_fail) {
$('#login-error').removeClass('display-hide');
}
else if (data.forget_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
else if (data.forget_user_fail) {
$('#forget-user-error').removeClass('display-hide');
}
else if (data.reset_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).removeClass('hidden');
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
})
.fail(function (jqXHR, ajaxOptions, thrownError) {
alert('No response from server');
});
return false;
});
How can I route to the other page on success condition? The ajax is triggered on a form submit button.
As you are doing an ajax request you can't just redirect from the controller on successful validation. Instead, just return the url you want to redirect to, as response to the ajax request similar to the way you are returning the validation errors. And in your js file use that url to redirect to new page.
#your above code
else if (data.forget_user_fail) {
$('#forget-user-error').removeClass('display-hide');
}
else if (data.reset_fail) {
$.each(data.errors, function (index, value) {
var errorSpan = '#' + index + '_error';
$(errorSpan).removeClass('hidden');
$(errorSpan).empty().append(value);
});
$('#successMessage').empty();
}
else{
window.location.replace(data.redirect_url); //this will redirect to new page
}
})
.fail(function (jqXHR, ajaxOptions, thrownError) {
alert('No response from server');
});
return false;
});

Not getting Json object (having a collection) correctly in controller using ajax call

I am sending a json object to controller via ajax call, data property of ajax call showing correct data. On post to controller's method -received parameter having collection and its count is showing perfectly but the properties inside the collection is not showing values.
Here is the code -
Controller-
[HttpPost]
public ActionResult ImageOperations(ImageProcessingModel imageProcessingModel)
{
return Json("sucess");
}
Model-
public class ImageProcessingModel
{
public string Source { get; set; }
private List<ThumbnailImageSubTaskModel> _thumbnailImageSubTaskModel;
public List<ThumbnailImageSubTaskModel> ThumbnailImageSubTaskModel
{
get
{
if (_thumbnailImageSubTaskModel == null)
{
_thumbnailImageSubTaskModel = new List<ThumbnailImageSubTaskModel>();
}
return _thumbnailImageSubTaskModel;
}
}
}
js-
var ImageProcessingModel =
{
"Source": "test",
"ThumbnailImageSubTaskModel":allThumbnails.allItems()
}
allThumnails.allItems is ko.observableArray() which having values.
$.ajax({
url: '/ImageProcessingTask/ImageOperations',
type: 'Post',
data: ImageProcessingModel,
success: function (data, status) {
processEscapeKeyPress = true;
var fn = window[successCallback];
fn(data, passDataToCallback);
},
error: function (xhr, desc, err) {
alert(err);
processEscapeKeyPress = true;
processAjaxError(xhr, desc, err);
},
});
here ImageProcessingModel having all values and source is simple a string so this value is coming in the controller only the ThumbnailImageSubTaskModel showing counts but not its value.
Thanks!!
A common problem encoutered with sending JSON through AJAX to MVC. Many forget to set the type of data in their AJAX request.
Try setting the datatype and contentType:
$.ajax({
url: '/ImageProcessingTask/ImageOperations',
type: 'Post',
**contentType: 'application/json; charset=UTF-8',
dataType: 'json',**
data: ImageProcessingModel,
success: function (data, status) {
processEscapeKeyPress = true;
var fn = window[successCallback];
fn(data, passDataToCallback);
},
error: function (xhr, desc, err) {
alert(err);
processEscapeKeyPress = true;
processAjaxError(xhr, desc, err);
},
});

Pass ViewModel + Parameter to action using ajax call

How do I pass a view model and another parameter to my action method using jquery ajax?
with what I'm doing now, the action method is not being called. I think the cause is probably because the parameters are not being passed correctly in the data object of the jquery ajax call:
jQuery ajax:
$('#form-login').submit(function (event) {
event.preventDefault();
$.ajax({
url: "/Account/LogOn/",
data: $('#form-login').serialize(),
contentType: 'application/json; charset=utf-8',
success: function (data) {
if (data.userAuthenticated) {
window.location.href = data.url;
} else {
formBlock.clearMessages();
displayError($('#errorcred').val());
}
},
error: function () {
formBlock.clearMessages();
displayError($('#errorserver').val());
}
});
});
Action method (which accepts the view model and another parameter):
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl)
{
// Validate the email and password
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
FormsService.SignIn(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
if (Request.IsAjaxRequest())
{
return Json(new { userAuthenticated = true, url = returnUrl, isRedirect = true });
}
else
{
return Redirect(returnUrl);
}
}
else
{
if (Request.IsAjaxRequest())
{
return Json(new { userAuthenticated = true, url = Url.Action("Index", "Home"), isRedirect = true });
}
else
{
return RedirectToAction("Index", "Home");
}
}
}
}
else
{
if (Request.IsAjaxRequest())
{
return Json(new { userAuthenticated = false, url = Url.Action("LogOn", "Account") });
}
else
{
ModelState.AddModelError("", adm.ErrorUserNamePassword);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Remove the following from the $.ajax call:
contentType: 'application/json; charset=utf-8',
You have specified application/json encoding but the $('#form-login').serialize() function is sending application/x-www-form-urlencoded content.
As far as sending the returnUrl parameter is concerned, you could simply read it from the form action where it should be present (if you used the Html.BeginForm() helper):
$.ajax({
url: this.action,
...
});
Also you probably want to rename the event variable with something else as this is a reserved word in javascript:
$('#form-login').submit(function (e) {
e.preventDefault();
...
});
The only way I have found to do this is to just include the second parameter in your viewmodel and continue to serialize your form the way you are doing now.

MVC3 ajax action request: handling answer

I'm doing an Ajax request to an MVC3 action and I want to process the JsonResult in the success or error function.
Currently the behaviour is strange: Before hitting my breakpoint in the action it hits the error function.
Can anyone help me please and has a hint?
My view:
<form id="myForm">
//fields go here...
<button id="myButton" onclick="myFunction();">ButtonName</button>
</form>
The ajax call:
function myFunction() {
if ($('#myForm').valid() == false) {
return;
}
var data = {
val1: $("#val1").val(),
val2: $("#val2").val()
};
var url = "/Controller/Action";
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
cache: false,
data: data,
success: function (data, statusCode, xhr) {
alert('1');
if (data && data.Message) {
alert(data.Message);
alert('2');
}
alert('3');
},
error: function (xhr, errorType, exception) {
alert('4');
var errorMessage = exception || xhr.statusText;
alert("There was an error: " + errorMessage);
}
});
return false;
}
My action:
[HttpPost]
public ActionResult Action(Class objectName)
{
var response = new AjaxResponseViewModel();
try
{
var success = DoSomething(objectName);
if (success)
{
response.Success = true;
response.Message = "Successful!";
}
else
{
response.Message = "Error!";
}
}
catch (Exception exception)
{
response.Success = false;
response.Message = exception.Message;
}
return Json(response);
}
If you look in the ajax call I get directly the alert #4 and only then the action gets called which is too late. Unfortunately the exception is null. Directly after that the view gets closed.
You are not preventing the default onclick behavior. Can you try the following instead?
onclick="return myFunction()"

Resources