通过视图包将模型传递给j​​avascript空

时间:2014-01-21 07:00:21

标签: javascript jquery asp.net-mvc-3 json.net

我传递了我的类对象,然后将其序列化为json,然后将其访问为javascript,这将变为空白。

我的班级

public class PMICheckListWrapper
        {
            public PMIMachine Machine { get; set; }
            public List<PMICheckListResponse> CheckResponseList { get; set; }
        }

控制器代码:

public ActionResult GetViewEditData(int machineID)
        {
          var result = Json(PMIComputerModel.GetViewEditDetails(machineID), JsonRequestBehavior.AllowGet);
          ViewBag.MachineData = result.Data;
          return View("PMIComputerList");
        }

我正在访问它的JavaScript。

$(function(){
  if('@ViewBag.MachineData' != null)
        {
         var data = '@ViewBag.MachineData'; 
         alert(data);//this is coming empty
         alert(jQuery.parseJSON(data)); // this is coming null
        }

});

2 个答案:

答案 0 :(得分:1)

尝试使用

var data = @Html.Raw(@ViewBag.MachineData); 

答案 1 :(得分:0)

你对GetViewEditDetails实际上有什么东西有多确定?尝试:

public ActionResult GetViewEditData(int machineID)
    {
      var result = new JsonResult();
      var data = PMIComputerModel.GetViewEditDetails(machineID);
      if(data != null){
            result.Data = data;
      }
      else {
         // give some kind of feedback that there is no result
      }
      ViewBag.MachineData = result;
      return View("PMIComputerList");
    }