Render partial view with AJAX-call to MVC-action - ajax

I have this AJAX in my code:
$(".dogname").click(function () {
var id = $(this).attr("data-id");
alert(id);
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'html',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
});
});
The alert gets triggered with the correct value but the AJAX-call does not start(the method does not get called).
Here is the method that im trying to hit:
public ActionResult GetSingleDog(int dogid)
{
var model = _ef.SingleDog(dogid);
if (Request.IsAjaxRequest())
{
return PartialView("_dogpartial", model);
}
else
{
return null;
}
}
Can someone see what i am missing? Thanks!

do you know what error does this ajax call throws?
Use fiddler or some other tool to verify response from the server.
try modifying your ajax call as following
$.ajax({
url: '/Home/GetSingleDog',
dataType: 'string',
data: {
dogid: id,
},
success: function (data) {
$('#hidden').html(data);
}
error: function(x,h,r)
{
//Verify error
}
});
Also try
$.get("Home/GetSingleDog",{dogid : id},function(data){
$('#hidden').html(data);
});
Make sure, URL is correct and parameter dogid(case sensitive) is same as in controller's action method

Related

Ajax not returning desired results or not working at all

I have been trying to load return a JsonResults action from a controller in MVC using ajax call. I can see that the alert() function is triggering well but the ajax is not executing. I have search for several sources but to no avail.
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.Where(l3 => l3.LevelTwoItem_ID == selectedID);
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
The below too is the javascript calling for the json method.
<script>
function FillBussLicence_L3items() {
alert("You have clicked me");
var bl2_Id = $('#BussLicenceL2_ID').val();
//alert(document.getElementById("BussLicenceL2_ID").value);
alert(bl2_Id);
$.ajax({
url: 'StartSurvey/FillBusinessLicenceL3/' + bl2_Id,
type: "GET",
dataType: "JSON",
data: "{}", // { selectedID : bl2_Id },
//contentType: 'application/json; charset=utf-8',
success: function (bussLicence_L3items) {
$("#BussLicenceL3_ID").html(""); // clear before appending new list
$.each(bussLicence_L3items, function (i, licenceL3) {
$("#BussLicenceL3_ID").append(
$('<option></option>').val(licenceL3.LevelThreeItem_ID).html(licenceL3.LevelThreeItem_Name));
});
}
});
}
Also, I have tried this one too but no execution notice.
Thanks a lot for your help in advance.
After looking through the browser's console, I noticed that the LINQ query was tracking the database and was creating a circular reference so I changed the query to the following and voila!!
public JsonResult FillBusinessLicenceL3(int? selectedID)
{
var bl3_Items = db.LevelThreeItems.
Where(k => k.LevelTwoItem_ID == selectedID).
Select(s => new { LevelThreeItem_ID = s.LevelThreeItem_ID, LevelThreeItem_Name = s.LevelThreeItem_Name });
return Json(bl3_Items, JsonRequestBehavior.AllowGet);
}
There was nothing wrong with the ajax call to the controller.

ajax - request error with status code 200

From client side, I wanna send some data to server and receive some <div> tags which responding from View (another controller).
My ajax code looks like this:
var sortTopic = function () {
var $list = [],
$address = '',
$formData = new FormData();
/* do something here to set value to $list and $address */
$formData.append('Category', $list);
$formData.append('Address', $address);
$formData.append('Tags', '[KM]');
$formData.append('Skip', 0);
$.ajax({
url: '/Topic/Sort',
type: 'POST',
data: $formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (data) {
if (!data.success) {
$('.jumbotron').html(data.ex);
} else {
$('.jumbotron').html(data);
}
},
error: function (xhr) {
alert(xhr.status); //xhr.status: 200
}
});
};
In TopicController, action Sort was:
[AllowAnonymous]
[HttpPost]
public ActionResult Sort(SortTopicViewModel model)
{
try
{
if (model.IsValidSortTopicModel())
{
return PartialView("../Home/_Timeline", new TopicMaster().Sort(model));
}
return Json(new { success = false, ex = "Invalid model." });
}
catch (Exception e) { return Json(new { success = false, ex = e.Message }); }
}
I'm sure that the model is valid and method new TopicMaster().Sort(model) was working fine (because I had put breakpoint to view the return data). And the partial view _Timeline is a partial view of HomeController.
My problem is: I don't understand why I get error with status code 200 in ajax:
error: function (xhr) {
alert(xhr.status); //xhr.status: 200
}
Can you explain to me?
Thank you!
as you told you receive <div> in response that is not json and you mention dataType:"json" in your ajax just remove it. this will solve your problem. error 200 occur when you did not get valid response which is you mention in ajax.
for mor information you can read it documentation

MVC Ajax Post error

I am getting error while I post Ajax request to controller method. In controller method I need to pass Model class object.
But it gives me 500 Internal server error.
Can anybody help me to make it correct?
Mu code is as per below:
jQuery:
var request = $("#frmHost").serialize();
$.ajax({
url: "/Host/HostItemDetails/" ,
type: "POST",
datatype: 'json',
contentType : "application/json",
data: request,
success: function (data) {
if (data == '1111') {
///Success code here
}
else if (data != '') {
jAlert(data);
}
}
});
Controller Method :
[HttpPost]
public JsonResult HostItemDetails(ClsHost objHost)
{
//Code here
return Json("1111");
}
Nirav Try this,
Parse the serialized data as a JSON object and later stringify that while posting using JSON.stringify().
$("#Button").click(function () {
var data = $("#frmHost").serialize().split("&");
var request = {};
for (var key in data) {
request[data[key].split("=")[0]] = data[key].split("=")[1];
}
$.ajax({
url: "/Home/HostItemDetails/",
type: "POST",
datatype: 'json',
contentType: "application/json",
data: JSON.stringify(request),
success: function (data) {
if (data == '1111') {
///Success code here
}
else if (data != '') {
jAlert(data);
}
}
});
});
I ran the same code that you are running.
To test the code I did the following changes. I took a button, and on click event I am sending the post back to the controller.
the '[HttpPost]' attribute is fine too.
Can you make one thing sure, that the frmHost data matches to the class ClsHost,but still that shouldn't cause the server error, the error will be different.
$(document).ready(function () {
$("#clickMe").click(function () {
var request = '{"Users":[{"Name":"user999","Value":"test"},{"Name":"test2","Value":"test"}]}';
$.ajax({
url: "/Home/HostItemDetails/",
type: "POST",
datatype: 'json',
contentType: "application/json",
data: request,
success: function (data) {
if (data == '1111') {
///Success code here
}
else if (data != '') {
jAlert(data);
}
}
});
});
});
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult HostItemDetails(ClsHost objHost)
{
//Code here
return Json("111", JsonRequestBehavior.AllowGet);
}
It is solved by removing same property name in Model class. It is mistakenly added by me twice.

Model is not passed to controller's action

I have the following code:
<script type="text/javascript">
$('#btnConfirmAddition').click(function () {
var contractorId = $("#contractorId").val();
var contactPerson = $("#addNewContactPersonForm").serialize();
$.ajax({
url: '#Url.Action("AddContactPerson", "Contractors")',
type: "GET",
data: { newContactPerson: contactPerson, contractorId: contractorId },
//data: contactPerson,
success: function (data) {
$("#myModal").modal('hide');
toastr.success("Success");
location.reload();
},
error: function (data) {
$("#errorArea").html(showError(data.ErrorMessage));
toastr.error(data.errorMessage);
}
});
return false;
});
</script>
public JsonResult AddContactPerson(ContactPerson newContactPerson, string contractorId)
{
//Some code
}
When I pass parameters in ajax call as above, my newContactPerson is null and contractorId contains appropriate data.
However when remove contractorId parameter from controller's action and pass parameter in ajax call as follows:
data: contactPerson
it works. I was wondering why? Can someone please help me?
post your data following way,
data: $("#addNewContactPersonForm").serialize() + '&contractorId='+ contractorId
And add data type to Ajax call,
dataType: "json"

ajax call results in error instead of succes

In my ASP.net mvc3 project, i use a ajax call to send json data to a create actionmethod in the controller Company. But when i debug the ajax call, it always end up in a error result instead of the succes result.
ajax call:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'Json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function () {
alert('ajax call not successful');
}
});
My action method in the Company controller :
[HttpPost]
public ActionResult Create (Company company)
{
try
{
//Create company
CompanyRepo.Create(company);
return null;
}
catch
{
return View("Error");
}
}
I already debugged the actionmethod, but he completes it like he should.
So the data send with the ajax call will be handled and written to the db. (the action method does not use the catch part).
Why is my ajax call still gives the message 'ajax call not succesful'?
I used to got same problem with getting back the JSON result.
What I did is to set the dataType to "text json" :))
If this doesn't help try to get additional info by acquiring details of your error, i.e.:
$.ajax({
url: '/Company/Create',
type: 'POST',
data: JSON.stringify(CreateCompany),
dataType: 'text json',
contentType: 'application/json; charset=utf-8',
success: function () {
alert('ajax call successful');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
}
});
BTW: I found this solution somewhere on the StackOverflow
Why are you returning null in case of success in your controller action? Return something to success like for example a JSON object (especially as you indicated in your AJAX request that you expect JSON response from the server - using the dataType: 'json' setting - which should be lowercase j by the way):
return Json(new { success = true });
Wouldn't this just be easier:
$.post("/Company/Create", function (d) {
if (d.Success) {
alert("Yay!");
} else {
alert("Aww...");
}
}, "json");
And in your controller.
[HttpPost]
public JsonResult Create(
[Bind(...)] Company Company) { <- Should be binding
if (this.ModelState.IsValid) { <- Should be checking the model state if its valid
CompanyRepo.Create(Company);
return this.Json(new {
Success = true
});
};
return this.Json(new {
Success = false
});
}

Resources