2010-05-10 3 views
3

을 수락하지 그러나MVC JsonResult 방법 나는 하나 개의 문자열 매개 변수를 받아들이는 MVC JsonResult 방법이 매개 변수

 //Fetch Destinations 
     $("#Country").change(function() { 
      var countryId = $("#Country > option:selected").attr("value"); 
      $("#Destination").html(""); 
      $("#Resort").html(""); 
      $("#Resort").append($("<option></option>").val(0).html("---Select---")); 
      $.ajax({ 
       type: "POST", 
       traditional: true,      
       url: "/Destinations/GetDestinations", 
       data: "{countryId:'" + countryId + "'}", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: function (msg) { 
        BindDestinationSelect(msg) 
       } 
      }); 
     }); 

을의 JsonResult는 만에 보인다 널 (NULL) 매개 변수를 수신하십시오. 방화범이 매개 변수가 전달되고 있음을 보여주고있다하더라도 :

JSON 이 "11" 소스 을 countryId {countryId : '11 '}

어떤 아이디어가? 감사합니다

+0

FWIW,' "{countryId : '"+ countryId + "'}"'는 JSON이 아닙니다. JSON에는 큰 따옴표가 필요합니다. Firebug에서 POST 요청을 볼 때 http://www.json.org/json2.js와 같은 객체를 사용하여 객체를 JSON 형식 – R0MANARMY

답변

1

나는 문제가 실제로 데이터를 전달하는 방법에 생각, 당신은 문자열로 그렇게됩니다

data: "{countryId:'" + countryId + "'}", 

때 현실에서, 클라이언트 측에 구조를 사용한다;

data: { countryId: countryId }, 

jQuery는 올바르게 전달 된 ID를 처리 할 수 ​​있어야합니다. 지금하고있는 것처럼 JSON을 서버로 보내려고합니다. MVC가 기대하지 않는 것이고 이름/값 쌍이있는 POST가 필요합니다.

또한 jQuery Form Plugin을 고려하면 자바 구조를 POST 데이터 매우으로 직렬화 할 수 있습니다.

+1

으로 직렬화하면 이름/값 쌍이 전달됩니다. 그리고 매개 변수를 전달하는이 방식은 MVC 메서드를 호출하는 것과는 대조적으로 웹 서비스를 호출 할 때 작동합니다. – StephenLewes

1

아, 검색을 많이 한 후 실패한 이유를 발견했습니다.

아무것도 등 잘못된 JSON과 함께 할 수 없습니다, 오히려 사실은 컨트롤러 메소드 나던 당신이 그것을 JSON 값을 전달하려고하면 무엇을 기대 알고 :

http://www.c-sharpcorner.com/Blogs/BlogDetail.aspx?BlogId=863

그래서 내 경우에는 내가 '를 방금 단일 문자열 값을 전달하기로 선택했습니다.

다음
0
public JsonResult BindAllData(string Userid) 
    { 

     List<VoteList> list = new List<VoteList>(); 
     var indexlist = db.TB_WebSites.ToList(); 
     int i = 0; 
     var countlist = db.Tb_Votes.ToList(); 
     var VCountList = db.Tb_Votes.ToList(); 
     foreach (TB_WebSites vt in indexlist) 
     { 
      bool voted = false; 
     } 

     return Json(new { List = _list }); 

    } 


    function DataBind() { 
     $("#LoadingDatas").show(); 
     var userid = $("#FBUserId").text(); 
     //alert('Data : ' + userid); 
     var InnerHtml = ""; 
     $.ajax(
      { 
       url: '/Gitex/BindAllData/', 
       type: 'POST', 
       data: { "Userid": userid }, 
       dataType: 'json', 
       async: true, 
       success: function (data) { 
        //alert('Done'); 
        //alert(data.List.length); 
        for (var i = 0; i < data.List.length; i++) { 

      }); 

    } 

나를 위해 jQuery를 기능 성공을했다,이 시도 -

[HttpPost] 
public JsonResult GetDestinations(string countryId) 
{ 
    List<Destination> destinations = new List<Destination>(); 

    string destinationsXml = SharedMethods.GetDestinations(); 
    XDocument xmlDoc = XDocument.Parse(destinationsXml); 
    var d = from country in xmlDoc.Descendants("Country") 
      from destinationsx in country.Elements("Destinations") 
      from destination in destinationsx.Elements("Destination") 
      where (string)country.Attribute("ID") == countryId 
      select new Destination 
      { 
       Name = destination.Attribute("Name").Value, 
       ID = destination.Attribute("ID").Value, 
      }; 
    destinations = d.ToList(); 

    return Json(new JsonResult { Data = destinations}, JsonRequestBehavior.AllowGet); 
} 
0

난 당신이 속성 HttpPost와 마찬가지로 당신의 행동을 장식하는 것이 좋습니다 기능 (목적지) :

 $("#Country").change(function() { 
      var countryId = $("#Country > option:selected").attr("value"); 
      $("#Destination").html(""); 
      $("#Resort").html(""); 
      $("#Resort").append($("<option></option>").val(0).html("---Select---")); 
      $.ajax({ 
       type: "POST", 
       traditional: true, 
       url: "/Destinations/GetDestinations", 
       data: "countryId=" + countryId, 
       success: function (msg) { 
        BindDestinationSelect(msg.Data) 
       } 
      }); 
관련 문제