2014-09-25 98 views
0

我想從控制器獲取數據使用ajax查看,但不成功。以下是我的代碼這工作正常,但沒有獲取數據。請幫助並糾正我,如果我錯過了我的代碼中的東西。如何從控制器獲取數據使用ajax請求查看 - asp.net mvc 4

以下是我的代碼。

@model MvcAppLearn.Models.Student 


<!DOCTYPE html> 
<html lang="en"> 
<head> 
    <title>This is tile</title> 
</head> 

<body> 

    @using (Html.BeginForm("Index", "popup", FormMethod.Get, new { id = "myform" })) 
    { 
     <p> 
      Find by name: @Html.TextBox("SearchString") 
      <button id="model-opener">Open dialog</button> 
     </p> 
     <div id="dialog-model" title="This is title"> 
      <p> 
       @Html.TextBoxFor(item => item.FirstName, new { id = "ffirst" })<br /> 
       @Html.TextBoxFor(item => item.LastName, new { id = "llast" })<br /> 
      </p> 
     </div> 

    } 


</body> 
</html> 

@section script 
{ 

    <script> 

     $(function() { 

      $("#dialog-model").dialog({ 
       autoOpen: false, 
       height: 300, 
       width: 340, 
       model: true, 
       show: { 
        effect: "shake", 
        duration: 100 
       }, 

      }); 

      $("#model-opener").click(function (e) { 
       e.preventDefault(); 

       var txtFirstName = $('#ffirst'); 
       var txtLastName = $('#llast'); 
       var txtSearch = $('#SearchString'); 

       $.ajax({ 
        url: '/popup/Index', 
        type: 'GET', 
        data: { 
         StudentId: txtSearch.val() 
        }, 
        success: function (data) { 

         txtFirstName.val(data.FirstName); //HERE IS THE PROBLEM IN GETTING VALUE 
         txtLastName.val(data.LastName); //HERE IS THE PROBLEM IN GETTING VALUE 

         $("#dialog-model").dialog("open"); 
        }, 

        error: function() { 
         alert("Oh noes"); 
        } 
       }); 

      }); 

     }); 


    </script> 

} 

下面是我的控制器

public ActionResult Index(int? StudentId) 
    { 
     if (StudentId == null) 
     { 
      StudentId = 2; 
      return View(); 
     } 
     using (var db = new StdContext()) 
     { 
      Student std = new Student(); 
      std = db.Students.Where(m => m.StudentId == StudentId).Single(); 
      return View(std); 
     } 

    } 

回答

0

你沒有返回數據,你就返回一個觀點:

return View(std); 

如果你只是想返回數據要使用JavaScript代碼的Student對象,那麼您可能只想將其作爲JSON數據返回:

return Json(std); 
+0

感謝您寶貴的答案,但如何獲取數據作爲JSON在AJAX?你能分享任何例子或代碼嗎?, – user3004110 2014-09-25 12:26:09

+0

@ user3004110:嗯,想到的第一個例子是你的問題中的代碼。成功處理程序中的'data'對象應該是JSON序列化的'Student'對象。 – David 2014-09-25 12:27:31

+0

您需要控制器中的jsonResult方法 – 2014-09-25 13:29:40

相關問題