2010-05-10 7 views
3

У меня есть метод MVC JsonResult, который принимает один строковый параметр:MVC JsonResult метод не принимает параметр

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); 
    } 

С методом Jquery вызывающего метода:

 //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, кажется, только получить нулевой параметр. Несмотря на то, Firebug показывает, что параметр передается:

JSON CountryId "11" Источник {CountryId: '11' }

Любые идеи? Благодаря

+0

FWIW, '" {countryId: '"+ countryId +"'} "' не JSON. JSON требует двойных кавычек. Вы действительно должны использовать что-то вроде http://www.json.org/json2.js для сериализации объектов в формате JSON – R0MANARMY

ответ

1

Я думаю, что проблема заключается в том, как вы на самом деле передавая данные, вы делаете так, как строка:

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

Когда на самом деле, вы должны использовать структуру на стороне клиента;

data: { countryId: countryId }, 

jQuery должен иметь возможность правильно обрабатывать идентификатор. Поскольку вы делаете это сейчас, он пытается отправить JSON на сервер, который не является ожидаемым MVC, он ожидает POST с парами имя/значение.

Вы также можете рассмотреть jQuery Form Plugin, так как он сериализует ваши структуры Javascript в данные POST очень легко.

+1

, когда я смотрю запрос POST в Firebug, он передает пару имя/значение. И этот же способ передачи параметров работает, когда я вызываю веб-сервис (в отличие от вызова метода MVC) – StephenLewes

1

Ах, после долгих поисков я обнаружил причину, по которой он терпит неудачу.

Ничего не делать с искаженной JSON и т.д., а тот факт, что метод контроллер не знает, чего ожидать, если вы пытаетесь передать его значение в формате JSON:

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

Так что в моем случае, я вы просто решили передать ему одно строковое значение.

 $("#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) 
       } 
      }); 
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 успеха: функция (назначения)

0

Здесь я предлагаю вам украсить свое действие с HttpPost атрибут как: -

[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); 
} 
Смежные вопросы