재우니의 블로그



How Do I: Return JSON Formatted Data for an AJAX Call in an ASP.NET MVC Web Application?


http://www.asp.net/mvc/videos/how-do-i-return-json-formatted-data-for-an-ajax-call-in-an-aspnet-mvc-web-application


<head> 
<script type="text/javascript" src="../../Scripts/jquery-1.4.1.min.js"></script> 
<script type="text/javascript"> 
$(document).ready(function () { 
$("#CategoryId").change(function () { 
 
    var categoryId = $(this)[0].value; 
 
    $("#ctl00_MainContent_SubcategoryId").empty(); 
    $("#ctl00_MainContent_SubcategoryId").append("<option value=''>-- select a category --</option>"); 
    var url = "/Subcategory/Subcategories/" + categoryId; 
 
    $.getJSON(url, { "selectedItem": "" }, function (data) { 
        $.each(data, function (index, optionData) { 
            $("#ctl00_MainContent_SubcategoryId").append("<option value='" + optionData.SubcategoryId + "'>" + optionData.SubcategoryName + "</option>"); 
        }); 
        //feed our hidden html field 
        var selected = $("#chosenSubcategory") ? $("#chosenSubcategory").val() : ''; 
        $("#ctl00_MainContent_SubcategoryId").val(selected); 
 
    }); 
 
}).change(); 
}); 
</script> 
<body> 
<% using (Html.BeginForm()) {%> 
<label for="CategoryId">Category:</label></td> 
<%= Html.DropDownList("CategoryId", (SelectList)ViewData["Categories"], "--categories--") %> 
<%= Html.ValidationMessage("category","*") %> 
<br/> 
<label class="formlabel" for="SubcategoryId">Subcategory:</label><div id="subcategoryDiv"></div> 
<%=Html.Hidden("chosenSubcategory", TempData["subcategory"])%> 
<select id="SubcategoryId" runat="server"> 
</select><%= Html.ValidationMessage("subcategory", "*")%> 
<input type="submit" value="Save" /> 
<%}%>                 



cs 단.



public class SubcategoryController : Controller 
    private MyEntities db = new MyEntities(); 
 
    public int SubcategoryId { get; set; } 
    public int SubcategoryName { get; set; } 
    public JsonResult Subcategories(int? categoryId) 
    { 
        try 
        { 
            if (!categoryId.HasValue) 
                categoryId = Convert.ToInt32(RouteData.Values["id"]); 
            var subcategories = (from c in db.Subcategories.Include("Categories") 
                                 where c.Categories.CategoryId == categoryId && c.Active && !c.Deleted 
                                  && c.Categories.Active && !c.Categories.Deleted 
                                 orderby c.SubcategoryName 
                                 select new { SubcategoryId = c.SubcategoryId, SubcategoryName = c.SubcategoryName } 
            ); 
            //just added the allow get attribute 
            return this.Json(subcategories, JsonRequestBehavior.AllowGet); 
        } 
        catch { return this.Json(null); } 
 
    }