开发者

Trying to return data asynchronously using jQuery AND jSon in MVC 2.0

开发者 https://www.devze.com 2023-01-02 07:51 出处:网络
I am trying to use Jquerys getJSON method to return data server side to my browser, what happens is the url the getJSON method points to does get reached but upon the postback the result does not get

I am trying to use Jquerys getJSON method to return data server side to my browser, what happens is the url the getJSON method points to does get reached but upon the postback the result does not get returned to the browser for some odd reason. I wasen't sure if it was because I was using MVC 2.0 and jQuery 1.4.1 and it differs to the MVC 1.0 version and开发者_Python百科 jQuerys 1.3.2 version. . this is the code sections

Controller

public JsonResult StringReturn() {
    NameDTO myName = new NameDTO();
    myName.nameID = 1;
    myName.name = "James";
    myName.nameDescription = "Jmaes";

    return Json(myName);
}

View with JQuery

<script type="text/javascript">
$(document).ready(function() {

  $("#myButton").click(function() {
    $.getJSON("Home/StringReturn/", null, function(data) {
      alert(data.name);
      $("#show").append($("<div>" + data.name + "</div>"));
    });
  });
});
</script>

HTML

<input type="button" value="clickMe" id="myButton"/>
<div id="show">d</div>


  • Are you sure about your path "Home/StringReturn/" ?
  • Replace null with an empty string "" or just skip it
  • Notice this text from jQuery API

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.


I figured out I need to use JsonRequestbehavior inside the return type method to allow get requests

return Json(myName, JsonRequestBehavior.AllowGet);

now it works.

0

精彩评论

暂无评论...
验证码 换一张
取 消