I am using asp.net webapi controller and in my project I have a dll that I created. A dll is used to check if the person that the user enters exists.
Here is my controller method:
// POST: api/EventsAPI [ResponseType(typeof(Event))] public IHttpActionResult PostEvent(Event @event) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (@event.DateEndOfEvent < @event.DateOfEvent) // successfully returns error.modelState (in view code) { ModelState.AddModelError("DateEndOfEvent", "End Date Cannot Be Before Start Date!"); return BadRequest(ModelState); } if (!EmpData.IsValid(@event.PersonWorkedOne)) // returns error.modelState as undefined (in view code) { ModelState.AddModelError("PersonWorkedOne", "This person does not exist!"); return BadRequest(ModelState); } if (!string.IsNullOrWhiteSpace(@event.PersonWorkedTwo)) { if (!EmpData.IsValid(@event.PersonWorkedTwo)) // returns error.modelState as undefined (in view code) { ModelState.AddModelError("PersonWorkedTwo", "This persondoes not exist!"); return BadRequest(ModelState); } } db.Event.Add(@event); db.SaveChanges(); return CreatedAtRoute("DefaultApi", new { id = @event.Id }, @event); }
Now the two conditional statements above that have EmpData .. EmpData from my dll.
Here is the ajax code in my opinion:
$("form").data("validator").settings.submitHandler = function(form) { $.ajax({ method: "POST", url: infoGetUrl, data: $("form").serialize(), success: function() { toastr.options = { onHidden: function () { window.location.href = newUrl; }, timeOut: 3000 } toastr.success("Event successfully created."); }, error: function (jqXHR, textStatus, errorThrown) { var status = capitalizeFirstLetter(textStatus); var error = $.parseJSON(jqXHR.responseText); var modelState = error.modelState; console.log(modelState); $.each(modelState, function (key, value) { var id = ""; if (key === "$id") { id = "#" + key.replace('$', '').substr(0, 1).toUpperCase() + key.substr(2); } else { id = "#" + key.replace('$', '').substr(0, 1).toUpperCase() + key.substr(1); var status = capitalizeFirstLetter(textStatus); console.log(key); toastr.error(status + " - " + modelState[key]); } var input = $(id); console.log(id);
Now in the controller, when I purposefully test to get an error message indicating the end date before the start date, I get error.modelState . But when I purposefully check for an error message saying that the person does not exist ... I do not get error.modelState .. which returns as undefined .
Is ModelState returned when using a custom DLL?
Any help is appreciated.
jquery c # ajax asp.net-mvc-5 asp.net-web-api2
GTown-Coder
source share