我的模型名为Student,它有三个属性:Id,Name,score。在我的视图中,我使用模型绑定,在我的操作中,我搜索学生并返回学生信息,但即使我使用ModelState.Clear()
看起来这个代码不起作用,视图总是向学生显示id = 0。< / p>
模型:
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 :(得分:0)
如果要在视图中使用模型,则必须在开始时使用关键字@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);
}