2013-12-22 62 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); 
} 
相关问题