How do I get a single json value using Webmatrix / razor?

好久不见. 提交于 2019-12-11 02:20:56

问题


I am trying to grab just a single value from some json and am using Chrome's javascript console to try and debug it. I have tried Request["id"], and Request.Params["id"] and it doesn't grab anything. I have verified via the chrome javascript debugger that the value is going across but I can't pull the value out using webmatrix. Can anybody please help?

code from Default.cshtml

$.ajax({
    type: 'POST',
    data: encodedItemId, //looks like { id : value }
    dataType: 'json',
    url: '/actions/act_markCompleted.cshtml',
    success: function(data){
        alert(data); //trying to view the json data
    }
});

Posts via ajax to this page, act_markCompleted.cshtml

 @{
   var itemId = Request["id"];

   var data = "The id is: " + itemId;

   var db = Database.Open("VacationBuddyDB");
   var sql = "UPDATE Items SET completed = @0 WHERE Id = @1";

   db.Execute(sql, true, itemId.AsInt());

   Json.Write(data, Response.Output);
 }

回答1:


The following should work:

$.ajax({
    type: 'POST',
    data: { id : 'value' },
    dataType: 'json',
    url: '/actions/act_markCompleted.cshtml',
    success: function(data) {
        alert(data);
    }
});

Make sure that you are not sending { id : 'value' } as a string but rather as a javascript object as shown. Also if you are running this ajax request inside the callback of the click action of some link or form submit make sure that you cancel the default action by returning false at the end or the ajax request might not have time to execute.



来源:https://stackoverflow.com/questions/6637818/how-do-i-get-a-single-json-value-using-webmatrix-razor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!