2013-12-22 59 views
0

我的模特被稱爲學生,它有三個屬性:Id,Name,Score。在我看來,我使用模型綁定,並在我的行動中我搜索學生並返回學生信息,但即使我使用ModelState.Clear()它看起來像這個代碼不起作用,視圖總是顯示學生哪個id = 0。MVC:當我改變模型並返回視圖(模型)時,爲什麼我的視圖沒有改變?

型號

public class Student 
{ 
    public int Id{get;set;} 
    public string Name{get;set;} 
    public int Score{get;set;} 
} 

查看

@project.bll.Student 
@Html.TextBoxFor(model=>model.Name) 
@Html.TextBoxFor(model=>model.Score) 
$.ajax({ 
    url: "@Url.Action("GetStudent","Student")", 
    type: "post", 
    data: { "id": $("#Id").val() },//id is set to be 0 or 1 or 2 
    success: function (result) { 
    alert(result); 
    }}); 

控制器

public ActionResult GetStudent(int id=0) 
{ 
    //ModelState.Clear(); 
    return View(StudnetRepository.GetStudentById(id)); 
} 
+0

你調試你的控制器,使確定一個id正在傳遞給'GetStudent'函數? –

+0

是的,我可以將學生ID如0或1或2傳遞給控制器​​,但在視圖中始終顯示爲0的學生ID。 – Lyly

+0

JavaScript警報返回什麼? –

回答

0

如果你想使用A M奧德爾在你看來,你必須使用keywork @model在開始

所以你的視圖必須

@model YourNamespace.Student 
@Html.TextBoxFor(model=>model.Name) 
@Html.TextBoxFor(model=>model.Score) 
<script> 
    $.ajax({ 
     url: "@Url.Action("GetStudent","Student")", 
     type: "post", 
     data: { "id": $("#Id").val() },//id is set to be 0 or 1 or 2 
     success: function (result) { 
     alert(result); 
    }}); 
</script> 

比控制器必須實例化模型

public ActionResult GetStudent(int id=0) 
{ 
    var model = new Student(); 
    //get the student with repository 
    //valorize the studend with model.Id, name etc 
    return View(model); 
} 
相關問題