2011-08-25 2 views
1

내 요구 사항에 맞는 샘플 앱을 변환하는 데 문제가 있습니다. 나는 내가 뭘 잘못하고 있는지 파악할 수 없었습니다. 변환 된 앱에서 JSon 호출을 반환 한 후에도 알림 메시지가 표시되지 않습니다. 먼저 샘플의 모델, 컨트롤러 및 뷰를 복사합니다. 그런 다음 변환 된 앱의 모델, 컨트롤러 및보기를 복사합니다. 컨트롤러 호출시 중단 점을 치고 있는데 SelectList 데이터가 JSon 객체에 제대로 포장 된 것처럼 보입니다. 하지만 나는 틀린 일을해야만합니다. 문제를 이해하는 데 도움이 될 것입니다.MVC3 면도기 JSon/Javascript - 하나의 드롭 다운 상자 내용 다른 선택에 따라 다름

---------------------------- Working Sample Model ------------ 
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 

namespace SimpleMVCJSONSample.Models 
{ 
public class MyViewModel 
{ 
    public int? Year { get; set; } 
    public int? Month { get; set; } 

    public IEnumerable<SelectListItem> Years 
    { 
     get 
     { 
      return Enumerable.Range(2000, 12).Select(x => new SelectListItem 
      { 
       Value = x.ToString(), 
       Text = x.ToString() 
      }); 
     } 
    } 
} 
} 

-------------------------- Working Sample Controller ------------------ 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 

using System.Web.Mvc; 
using SimpleMVCJSONSample.Models; 

namespace SimpleMVCJSONSample.Controllers 
{ 

public class HomeController : Controller 
{ 
    public ActionResult Index() 
    { 
     var model = new MyViewModel(); 
     return View(model); 
    } 

    public ActionResult Months(int year) 
    { 
     if (year == 2011) 
     { 
      var jsonRet1 = Json(
       Enumerable.Range(1, 3).Select(x => new { value = x, text = x }), 
       JsonRequestBehavior.AllowGet 
      ); 
      return jsonRet1; 
     } 
      var jsonRet2 = Json(
      Enumerable.Range(1, 12).Select(x => new { value = x, text = x }), 
      JsonRequestBehavior.AllowGet 
     ); 
     return jsonRet2; 
    } 
} 
} 

-------------------------- Working Sample View ----------------- 

@{ 
ViewBag.Title = "Home Page"; 
} 

<h2>@ViewBag.Message</h2> 

@model SimpleMVCJSONSample.Models.MyViewModel 

@Html.DropDownListFor(
x => x.Year, 
new SelectList(Model.Years, "Value", "Text"), 
"-- select year --" 
) 

@Html.DropDownListFor(
x => x.Month, 
Enumerable.Empty<SelectListItem>(), 
"-- select month --" 
) 

<script type="text/javascript"> 
$('#Year').change(function() { 
    var selectedYear = $(this).val(); 
    if (selectedYear != null && selectedYear != '') { 
     $.getJSON('@Url.Action("Months")', { year: selectedYear }, function (months) { 
      alert(months); 
      var monthsSelect = $('#Month'); 
      monthsSelect.empty(); 
      $.each(months, function (index, month) { 
       monthsSelect.append($('<option/>', { 
        value: month.value, 
        text: month.text 
       })); 
      }); 
     }); 
    } 
}); 
</script> 

---------------------------------END OF Working SAMPLE----------------------- 

--------------------------My Converted Model ------------------------ 

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Mvc; 
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling; 
using ONSM.Common.Logging; 
using VW40.Data.Model; 
using VW40.Services; 

namespace VW40.Web.Models 
{ 
public class CompanyPeopleViewModel 
{ 
    private Log _log; 
    private ExceptionManager _exceptionManager; 
    private readonly ICompanyService _companyService; 
    private readonly IPersonService _personService; 

    public CompanyPeopleViewModel(Log log, ExceptionManager exceptionManager,  ICompanyService companyService, IPersonService personService) 
    { 

     _companyService = companyService; 
     _personService = personService; 
     _log = log; 
     _exceptionManager = exceptionManager; 
    } 

    public int Company { get; set; } 
    public int Person { get; set; } 

    public IEnumerable<SelectListItem> CompanySelectList 
    { 
     get 
     { 
      return _companyService.GetCompanies().OrderBy(x => x.CompanyName).Select(x => new SelectListItem 
        { 
         Value = x.CompanyID.ToString(), 
         Text = x.CompanyName 

        }); 
     } 
    } 
} 
} 

--------------------------- My Converted Controller ---------------- 

using System.Collections; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web.Mvc; 
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling; 
using ONSM.Common.Logging; 
using VW40.Data.Model; 
using VW40.MVC.Models; 
using VW40.Services; 
using VW40.Services.AccessControl; 
using VW40.Web.Models; 
using System.Web; 


namespace VW40.MVC.Controllers 
{ 
[Authorize(Roles = "Administrator")] 
public class AccessControlController : MembershipAdministrationController_Base 
{ 
    private Log _log; 
    private ExceptionManager _exceptionManager; 
    private IAccessControlService _accessControlService; 
    private IPersonService _personControlService; 
    private ICompanyService _companyService; 

    public AccessControlController(
     Log log, 
     ExceptionManager ExceptionManager, 
     IAccessControlService AccessControlService, 
     IPersonService PersonService, 
     ICompanyService CompanyService 
     ) 
    { 
     _log = log; 
     _exceptionManager = ExceptionManager; 
     _accessControlService = AccessControlService; 
     _personControlService = PersonService; 
     _companyService = CompanyService; 
    } 

    public ActionResult Json_CompanyPeopleSelectList(int CompanyID) 
    { 


     var companyPersonsList = _personControlService.GetPersonsByCompanyId(CompanyID).OrderBy(x => x.Lastname + x.Firstname); 

     //IEnumerable<SelectListItem> myList = companyPersonsList.Select(x => new SelectListItem 
     //                  { 
     //                    Value = x.PersonID.ToString(), 
     //                   Text = x.Lastname 
     //                  } 
      //); 


     var jsonRet = 
      Json(
       _personControlService.GetPersonsByCompanyId(CompanyID).OrderBy(x => x.Lastname + x.Firstname).Select 
        (x => new 
           { 
            value = x.PersonID.ToString(), 
            text = x.Lastname 
           }), JsonRequestBehavior.AllowGet); 
     return jsonRet; 
    } 

--------------------------- 내 변환 된보기 ------------- ----

@model VW40.Web.Models.CompanyPeopleViewModel 
@{ 
Layout = "~/Views/Shared/SiteLayout.cshtml"; 
ViewBag.Title = "UserPermissions"; 
} 

<h2>UserPermissions</h2> 

@Html.DropDownListFor(
x => x.Company, 
new SelectList(Model.CompanySelectList, "Value", "Text"), 
"Select Company" 
) 

@Html.DropDownListFor(
    x => x.Person, 
    Enumerable.Empty<SelectListItem>(), 
    "-- Select Person --" 
) 
<script type="text/javascript"> 
$('#Company').change(function() { 
    var selectedCompany = $(this).val(); 
    if (selectedCompany != null && selectedCompany != '') { 
     $.getJSON('@Url.Action("Json_CompanyPeopleSelectList")', { CompanyID:  selectedCompany }, function (listOfCompanyPeople) { 
      alert(listOfCompanyPeople); 
      var personSelect = $('#Person'); 
      personSelect.empty(); 
      $.each(listOfCompanyPeople, function (index, person) { 
       personSelect.append($('<option/>', { 
        value: person.value, 
        text: person.text 
       })); 
      }); 
     }); 
    } 
}); 
</script> 

------------------------------ end of Conversion ---------------- 

답변

0

당신은 직접 브라우저에 URL을 입력하여 컨트롤러를 호출하고 올바른 JSON 데이터를 반환 여부를 볼 수 있었다. getJSON에 오류 핸들러 함수가 없으므로 JSON 응답이 서버에서 올바르게 리턴되지 않았는지 확인할 수 없습니다.

http://jquery-load-json.googlecode.com/svn/trunk/categories-ajax.html에는 유사한 예가 하나 있습니다. 이 예제에서 첫 번째 카테고리 드롭 다운은 한 번의 호출로로드되고 종속 드롭 다운은 보조 Ajax 호출을 사용하여로드됩니다. 이 예제를 사용하는 경우 회사의 사용자 목록을 반환하는 컨트롤러를 만들고 loadJSON을 사용하여 하위 범주 드롭 다운에 반환 된 값을 채 웁니다.

조반

관련 문제