I am trying to use .ajax() to post a People object to a MVC2 action that expects a ViewModel as parameter. The ViewModel has a People property.
The problem is that when the MVC action is activated, the ajax() postback People object is always null. I used Fiddler to diagnose the problem. The property values in the People object are all contained in the header. Here is my client jQuery script. Please note that I used three methods to stuff the property values into People object, but none of them works.
StaffDlg.delegate("#SaveButton", "click",
function (e) {
e.preventDefault();
People["PKey"] = $("#PKey").val();
People["FName"] = $("#FName").val();
People["LName"] = $("#LName").val();
People["MName"] = $("#MName").val();
People["SSN"] = $("#SSN").val();
People["Gender"] = $("#Gender").val();
People["DOB"] = $("#DOB").val();
People["BirthPlace"] = $("#BirthPlace").val();
People["NetworkAccount"] = $("#NetworkAccount").val();
var pkey = $("#PKey").val();
var action;
if (!isNaN(parseFloat(pkey)) && isFinite(pkey)) {
action = "Edit" + "/" + pkey;
}
else {
action = "Create";
}
$.ajax({
url: getRootUrl() + "/Staff/" + action,
//data: { FName: $("#FName").val(), LName: $("#LName").val(), MName: $("#MName").val(),
// SSN: $("#SSN").val(), Gender: $("#Gender").val(), DOB: $("#DOB").val(),
// BirthPlace: $("#BirthPlace").val(), NetworkAccount: $("#NetworkAccount").val()
//},
//data: JSON.stringify(People),
data: $("Form").serialize(),
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (result) {
$("#ajaxResponse").addClass("whiteOnGreen").html("Update succeeded");
},
error: function (qXHR, textStatus, errorThrown) {
$("#ajaxResponse").addClass("whiteOnRed").html("Failed to save the record!\r\n" +
textStatus + ": " + errorThrown + "\r\n" +
"data : " + JSON.stringify(People));
}
})
}
);
and here is the MVC action.
public ActionResult Edit(int id, StaffViewModel updatedStaff)
{
People staff = _staffService.GetStaff(id);
if (updatedStaff == null)
return View("NotFound");
if (ModelState.IsValid)
{
TryUpdateModel<People>(staff, "staff");
staff.RecordLastUpdated = DateTime.Now;
staff.UpdatedBy = HttpContext.User.Identity.Name;
_staffService.SaveStaff();
//return RedirectToAction("Index", new { id = thisStaff.PKey });
if (Request.IsAjaxRequest())
return this.Json(staff, JsonRequestBehavior.AllowGet);
else
{
if (string.IsNullOrEmpty(updatedStaff.previousURL))
return Redirect("/Staff/Startwith/" + staff.LName.Substring(1, 1));
else
return Redirect(updatedStaff.previousURL);
}
}
else
{
if (Request.IsAjaxRequest())
{
string errorMessage = "<div class='whiteOnRed error'>"
+ "The following errors occurred:<ul>";
foreach (var key in ModelState.Keys)
{
var error = ModelState[key].Errors.FirstOrDefault();
if (error != null)
{
errorMessage += "<li>"
+ error.ErrorMessage + "</li>";
}
}
errorMessage += "</ul></div>";
return Json(new { Message = errorMessage });
}
else
return View(updatedStaff);
}
}
You state that the form expects a StaffViewModel as a parameter, and a StaffViewModel has a People property... but you are not passing the full StafFViewModel object - instead you are passing a People object from the Ajax call, and hoping that the People property gets populated on the MVC end.
There is a disconnect there and the auto-binder doesn't know how to bridge it.
Try creating a controller method with a (int, People) signature, and see if that works for you.
Otherwise, you might need to create a custom binder.
Try removing dataType and contentType settings from your ajax call:
$.ajax({
url: getRootUrl() + "/Staff/" + action,
data: $("Form").serializeArray(),
type: "POST",
success: function (result) {
$("#ajaxResponse").addClass("whiteOnGreen").html("Update succeeded");
},
error: function (qXHR, textStatus, errorThrown) {
$("#ajaxResponse").addClass("whiteOnRed").html("Failed to save the record!\r\n" +
textStatus + ": " + errorThrown + "\r\n" +
"data : " + JSON.stringify(People));
}
})
I solved the problem with the .ajax() not posting the form values to the MVC Create(People person) action. It was the parameter type that this different than the one used in Edit(StaffViewModel). Now both action accept the same type of parameter, StaffViewMode.
Related
This is how my web api action look like.
[System.Web.Http.HttpPost, System.Web.Http.Route("BookAppointment/{email}/{id}")]
public System.Net.Http.HttpResponseMessage BookAppointment(string email, int id = 0)
{
System.Net.Http.HttpResponseMessage retObject = null;
if (id > 0 && email!="")
{
UserAppointmentService _appservice = new UserAppointmentService();
bool success = _appservice.BookAppointment(email,id);
if (!success)
{
var message = string.Format("error occur for updating data", id);
HttpError err = new HttpError(message);
retObject = Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, err);
retObject.ReasonPhrase = message;
}
else
{
retObject = Request.CreateResponse(System.Net.HttpStatusCode.OK, "SUCCESS");
}
}
else
{
var message = string.Format("doc id and emial can not be zero or blank");
HttpError err = new HttpError(message);
retObject = Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, err);
retObject.ReasonPhrase = message;
}
return retObject;
}
This is my jquery ajax code which suppose to call web api action but throwing error. the error is
No HTTP resource was found that matches the request URI
'http://localhost:58782/api/Appointments/BookAppointment'.
My jquery ajax code as follows.
$('#tblAppointments').on('click', '#btnbook', function () {
var docid = $(this).closest('tr').find("input[id*='hdndocid']").val();
var email = $(this).closest('tr').find("input[id*='hdnpatientemail']").val();
var baseurl = '#ConfigurationManager.AppSettings["baseAddress"]' + 'api/Appointments/BookAppointment';
// + encodeURIComponent(email) + '/' + docid;
alert(baseurl);
$.ajax({
url: baseurl,
type: 'POST',
dataType: 'json',
contentType: "application/json",
data: JSON.stringify({ email: encodeURIComponent(email), id: docid}),
success: function (data, textStatus, xhr) {
console.log(data);
},
error: function (xhr, textStatus, errorThrown) {
var err = eval("(" + xhr.responseText + ")");
alert('Error ' + err.Message);
console.log(textStatus);
}
}).done(function () {
});
});
I have only default route in web api config.
Please tell me what kind of mistake i have done for which it is not working. thanks
There are more problems with your code so I will try to explain them step by step.
1.Based on the code you have provided, you must have decorated your controller with a route like
[RoutePrefix("api/appointments")]
in order to correctly call the BookAppointment method.
If you decorate your controller with this attribute, then you can simply call
http://localhost/api/appointments/BookAppointment/testemail#domain.com/1
and the method would be 100% called.
2.The following code:
var baseurl = '#ConfigurationManager.AppSettings["baseAddress"]' + 'api/Appointments/BookAppointment';
// + encodeURIComponent(email) + '/' + docid;
translates into something like
http://localhost/api/Appointments/BookAppointment
so the necessary part (email/id) are not given (that's why the error message is given).
3.The javascript code makes a POST with JSON in body but your API is not accepting JSON body.
I recommend that you create a separate class like this:
public class BookAppointmentRequest
{
public string Email { get; set; }
public int ID { get; set; }
}
And after that, you modify the method in order to specify that you are accepting data from body.
[HttpPost, Route("BookAppointment")]
public HttpResponseMessage BookAppointment([FromBody] BookAppointmentRequest request)
After that, you can simple make a POST to api/Appointments/BookAppointment with the JSON from your javascript code.
I recommend you to use IHttpActionResult instead of HttpResponseMessage. See this link.
I am new to ajax and I am trying to return a list of entity objects via ajax. When I do this with string it works successfully.
my ajax code:
$.ajax({
type: "POST",
url: "/MemberPages/AdminPages/AddProduct.aspx/GetList",
data: '{"categoryId":' + $('#<%=ddlCategory.ClientID %> option:selected').val() + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var cats = msg.d;
$.each(cats, function (index, cat) {
alert(cat);
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
my code that returns a string:
[WebMethod]
public static List<String> GetList(int categoryId)
{
List<String> catlist = new List<String>();
IQueryable<SubCategory> clist = new ProductsBL().GetSubCategories(categoryId);
foreach (SubCategory c in clist)
{
catlist.Add(c.Name.ToString());
}
return catlist;
}
my code that gives a 500 internal server error
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static List<SubCategory> GetList(int categoryId)
{
List<SubCategory> catlist = new List<SubCategory>();
IQueryable<SubCategory> clist = new ProductsBL().GetSubCategories(categoryId);
foreach (SubCategory c in clist)
{
catlist.Add(c);
}
return catlist;
}
Thanks For any help as I have spent a considerable amount of time trying to wrap my head around it.
I think you have to remove the external quotes to the "data" in the jQuery call
data: {categoryId: $('#<%=ddlCategory.ClientID %> option:selected').val() },
Otherwise you submit a String, not the intended request composed by parameter called categoryId and valued as extracted from the selected option
I have the following $.ajax post call. It would go through the action being called but then it would trigger the "error" block of the function even before the actionresult finishes. Also, it seems to reload the whole page after every pass.
var pnameVal = '<%: this.ModelCodeValueHelper().ModelCode%>';
var eidVal = '<%: ViewBag.EventId %>';
var dataV = $('input[ name = "__RequestVerificationToken"]').val();
var urlVal = '<%: Url.Action("New") %>';
alert('url > ' + urlVal);
alert('pname - ' + pnameVal + ' eid - ' + eidVal + ' dataV = ' + dataV);
$.ajax({
url: urlVal,
//dataType: "JSONP",
//contentType: "application/json; charset=utf-8",
type: "POST",
async: true,
data: { __RequestVerificationToken: dataV, pname: pnameVal, eId: eidVal },
success: function (data) {
alert('successssesss');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
alert('dammit');
}
})
.done(function (result) {
if (result.Success) {
alert(result.Message);
}
else if (result.Message) {
alert(' alert' + result.Message);
}
alert('done final');
//$('#search-btn').text('SEARCH');
waitOff();
});
This is the action
[HttpPost]
public ActionResult New(string pname, int eid)
{
var response = new ChangeResults { }; // this is a viewmodel class
Mat newMat = new Mat { "some stuff properties" };
Event eve = context.Events.FirstOrDefault(e => e.Id == eid);
List<Mat> mats = new List<Mat>();
try
{
eve.Mats.Add(newMat);
icdb.SaveChanges();
mats = icdb.Mats.Where(m => m.EventId == eid).ToList();
response.Success = true;
response.Message = "YES! Success!";
response.Content = mats; // this is an object type
}
catch (Exception ex)
{
response.Success = false;
response.Message = ex.Message;
response.Content = ex.Message; // this is an object type
}
return Json(response);
}
Btw, on fiddler the raw data would return the following message:
{"Success":true,"Message":"Added new Mat.","Content":[]}
And then it would reload the whole page again. I want to do an ajax call to just show added mats without having to load the whole thing. But it's not happening atm.
Thoughts?
You probably need to add e.preventDefault() in your handler, at the beginning (I am guessing that this ajax call is made on click, which is handled somewhere, that is the handler I am talking about).
i have the following ajax.actionlink which calls a Delete action method for deleting an object:-
#if (!item.IsAlreadyAssigned(item.LabTestID))
{
string i = "Are You sure You want to delete (" + #item.Description.ToString() + ") ?";
#Ajax.ActionLink("Delete",
"Delete", "LabTest",
new { id = item.LabTestID },
new AjaxOptions
{ Confirm = i,
HttpMethod = "Post",
OnSuccess = "deletionconfirmation",
OnFailure = "deletionerror"
})
}
but is there a way to include #Html.AntiForgeryToken() with the Ajax.actionlink deletion call to make sure that no attacker can send a false deletion request?
BR
You need to use the Html.AntiForgeryToken helper which sets a cookie and emits a hidden field with the same value. When sending the AJAX request you need to add this value to the POST data as well.
So I would use a normal link instead of an Ajax link:
#Html.ActionLink(
"Delete",
"Delete",
"LabTest",
new {
id = item.LabTestID
},
new {
#class = "delete",
data_confirm = "Are You sure You want to delete (" + item.Description.ToString() + ") ?"
}
)
and then put the hidden field somewhere in the DOM (for example before the closing body tag):
#Html.AntiForgeryToken()
and finally unobtrusively AJAXify the delete anchor:
$(function () {
$('.delete').click(function () {
if (!confirm($(this).data('confirm'))) {
return false;
}
var token = $(':input:hidden[name*="RequestVerificationToken"]');
var data = { };
data[token.attr('name')] = token.val();
$.ajax({
url: this.href,
type: 'POST',
data: data,
success: function (result) {
},
error: function () {
}
});
return false;
});
});
Now you could decorate your Delete action with the ValidateAntiForgeryToken attribute:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id)
{
...
}
Modifying the answer by Bronx:
$.ajaxPrefilter(function (options, localOptions, jqXHR) {
var token, tokenQuery;
if (options.type.toLowerCase() !== 'get') {
token = GetAntiForgeryToken();
if (options.data.indexOf(token.name)===-1) {
tokenQuery = token.name + '=' + token.value;
options.data = options.data ? (options.data + '&' + tokenQuery)
: tokenQuery;
}
}
});
combined with this answer by Jon White
function GetAntiForgeryToken() {
var tokenField = $("input[type='hidden'][name$='RequestVerificationToken']");
if (tokenField.length == 0) { return null;
} else {
return {
name: tokenField[0].name,
value: tokenField[0].value
};
}
Edit
sorry - realised I am re-inventing the wheel here SO asp-net-mvc-antiforgerytoken-over-ajax/16495855#16495855
I have a View with Name, CreatedDate, Address, etc. In the Address section I have State, City etc. I made this section a Partial View.
By default there will be one address section in mainView. I have a button "AddAddress". I want to add another address section if user clicks the button (add a partial view). After getting this partial view there should be a remove button to remove this partial view. I am not using Razor.
the following code is my Javascript to delete my address.
function deleteAddress(addressId, clientId) {
var url1 = "/Client/DeleteAddress";
if (confirm("Are you sure you want to delete this address?")) {
var result = false;
$.ajax({
url: url1,
type: 'POST',
async: false,
data: { AddressId: addressId, ClientId: clientId },
dataType: 'json',
success: function (data) {
result = data;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
}
});
if (result) {
}
}
}
the following code is in my controller.
[HttpPost]
public JsonResult DeleteAddress(int AddressId, int ClientId)
{
if (AddressId != 0)
{
if (ClientId != 0)
{
ClientService.Client clientVuTemp = new ClientService.Client();
clientVuTemp = (ClientService.ClientView)TempData["EditClientData"];
clientVuTemp.Address.RemoveAt(AddressId);
//soft delete
clientVuTemp.Address[AddressId].IsActive = false;
_clientSvc.InserOrUpdateClientAddresses(clientVuTemp.Address);
}
else
{
}
return Json(true);
}
else
return Json(false);
}
In the Model we can have a property like IsAddAddressEnabled, Onclick on AddAddress you can set this as true and onclick on cancel you can set as false.
In View you can put an condition,
#if(Model.IsAddAddressEnabled)
{
Html.Partail(....)
}