This post is on Ajax-JSON in mvc4
In our application we have to display category and subcategories on Expand image button click.
following is the code which we followed......we used partial view for subcategories.
Partial View
---------------------------------------------------------------
@model IEnumerable
@{
}
View.cshtml
-------------------------------------------------------------------------------
name="@Html.Encode(dr["Category_Id"])" onclick="getSubCategories(@Html.Encode(dr["Category_Id"]));"/> | |||
@section Pagescripts
{
@Scripts.Render("~/bundles/jquery")
function getSubCategories(Category) {
var url = 'http://localhost/VendorRegistration/_partialSubCategory?Category='+ Category;
$.ajax({
url: url,
type: "POST",
contentType: 'application/json; charset=utf-8',
async: false,
processdata: false,
cache : false,
dataType: "json",
success: function (data) {
SetData(data);
},
error: function (data) { alert("error"); alert(data); }
});
function SetData(data) {
if (ajaxdiv.attr('id') == Category) {
$(".ajaxDiv").html(data);
}
}
}
}
Cotroller
-----------------------------------------------------------------------------------------------
public ActionResult _partialSubCategory(string Category)
{
int CategoryId = Convert.ToInt16(Category);
List subCatList = (from objSub in objbidportalEntity.bp_subcategory where objSub.categoryId == CategoryId
select new subcategory { CategoryId = (short)objSub.categoryId, SubCategoryCode = objSub.Subcategory_Code, SubCategoryDescription
= objSub.Description, SubCategoryId = objSub.Subcategory_Id, SubCategoryName = objSub.Subcategory_Name }).ToList();
return PartialView("_partialSubCategory", subCatList);
}
Model
---------------------------------------------------------------------------------------------------
public class VendorRegistrationStep3
{
public int VendorId { get; set; }
public int CategoryId { get; set; }
public string CategoryCode { get; set; }
public string CategoryDescription { get; set; }
public string CategoryName { get; set; }
public IEnumerable SubCategoryId { get; set; }
}
public class subcategory
{
public short CategoryId { get; set; }
public int SubCategoryId { get; set; }
public string SubCategoryCode { get; set; }
public string SubCategoryDescription { get; set; }
public string SubCategoryName { get; set; }
}
--------------------------------------------------------------------------------------------------------------------------------------------------------------The problem is we are not able to get onsuccess json data .we are getting OnError function.Unable to find where we went wrong.Please help us.
Prabhu RajaRank #861 · 2.6K reputationPosted Jan 9, 2014, 3:11 AM EST
Source Code
Jaganathan BantheswaranRank #170 · 14.1K reputationPosted Jan 8, 2014, 6:27 PM EST
Try to replace the ajax call as like this,
$.ajax({
url: 'http://localhost/VendorRegistration/_partialSubCategory',
type: 'POST',
data: JSON.stringify({Category: Category}),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
alert('Error: ' + xhr.statusText);
},
success: function (result) {
setData(result);
},
async: false,
processData: false
});
Prabhu RajaRank #861 · 2.6K reputationPosted Jan 8, 2014, 6:33 PM EST
And Please don't hardcode the URL in the ajax method. The Best Practise is,
url: '@Url.Action("_partialSubCategory","VendorRegistration"),
Sometimes it resolves the problem.
lakshmi sowmya69 reputationPosted Jan 8, 2014, 8:18 PM EST
I have changed my ajax as below.now its working .I am able to receive the html data with values of partial view.But the problem now is $(#div),html(data)
is not getting binded with the view.
I tried so many ways div.load,div.innerhtml........etc., but the html data is not getting binded.please do reply me.
Prabhu RajaRank #861 · 2.6K reputationPosted Jan 8, 2014, 8:30 PM EST
And if you want to load the partial view into the div element, then why you can simplify the code as like,
This is not tested. But you can try like this.
lakshmi sowmya69 reputationPosted Jan 8, 2014, 10:33 PM EST
Thanks Prabhu, I tried your solutions too.but its not working.
Its hitting the controller [HttpPost] action method of main view and returning the same old main view without any partial view.I am sending the image of what i am expecting the view should be.
Please suggest me any other solution if the way i am trying to make out is wrong.Help me out.
Prabhu RajaRank #861 · 2.6K reputationPosted Jan 8, 2014, 11:27 PM EST
to
If its not worked, let me know then i try to find some working examples.
Jaganathan BantheswaranRank #170 · 14.1K reputationPosted Jan 8, 2014, 11:44 PM EST
Did your view got updated after changing the url to
url: @Url.Action("_partialSubCategory","VendorRegistration")?
lakshmi sowmya69 reputationPosted Jan 9, 2014, 12:02 AM EST
I have changed @Url and ActionResult to PartialViewResult.
Even though my ajax div is getting loaded with the html.
When I debugged i can see data returned from ajax call but the view is not getting updated with partial view.
Unable to figure out where i went wrong.
Prabhu RajaRank #861 · 2.6K reputationPosted Jan 9, 2014, 12:13 AM EST
See,
name="@Html.Encode(dr["Category_Id"])" onclick="getSubCategories(@Html.Encode(dr["Category_Id"]));"/>
You are creating div with id as Category_Code but you are passing Category_Id to javascript function.
Change
onclick="getSubCategories(@Html.Encode(dr["Category_Id"]))
to
onclick="getSubCategories(@Html.Encode(dr["Category_Code"]))
And Try once.
lakshmi sowmya69 reputationPosted Jan 9, 2014, 1:05 AM EST
I have changed Category_code to Category_Id much before after my first post.Then only my Url got hitted in Json.
But now the problem is partial view is not displaying inside the div
I have tried $("#AjaxDiv").empty().append(data);After doing so i was able to see partial view blinked once in main view.But later its not coming....Its been a quite challenging issue for me.
you will be going to make my day.if you pull me out of this
lakshmi sowmya69 reputationPosted Jan 9, 2014, 7:26 PM EST
Thank u so much i have downloaded the source code and compared with mine.The difference was i wrote @Using(Html.BeginForm("Action","Controller") in the main view.cshtml.So after ajax call post back was happening to that action and main view is remaining same.
I removed it and now its working.
I am literally new to MVC so cant figure out this silly thing.Thanq once again.
Prabhu RajaRank #861 · 2.6K reputationPosted Jan 9, 2014, 8:17 PM EST
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questionsTop experts