2013-02-06 32 views
0

我有一张学生表,我想在存储在学生表中的个人档案页面上显示学生的名字。将数据从sql数据库拉入文本域

这就是我心目中的我的控制器:

public ActionResult StudentName(StudentModel model) 
{ 
    if(ModelState.IsValid) 
    { 
     using (var db = new SchoolDataContext()) 
     { 
      var result = from s in db.Students select s.StudentName; 
      model.StudentName = result.ToString(); 
     } 
    } 
} 
在我看来

我有:

@Html.LabelFor(s => s.StudentName) 
@Html.TextBoxFor(s => s.StudentName) 

我的模型:

public class StudentModel 
{ 
    [Display(Name = "Student Name")] 
    public string StudentName{ get; set; } 
} 

我需要一个GET方法来获得学生姓名显示在文本框中,同时有一个post方法,以便它可以保存,如果在单击保存后同一个框。

+0

我在这里看不到一个问题 –

+0

@四十二个我想知道如果我写或不为了什么,我有我的控制器。 – 072et

回答

0

也许您的控制器将是这个样子:

public ActionResult StudentName(int studentId)//you can't pass a model object to a get request 
{ 
     var model = new StudentModel(); 
     using (var db = new SchoolDataContext()) 
     { 
      //fetch your record based on id param here. This is just a sample... 
      var result = from s in db.Students 
         where s.id equals studentId 
         select s.StudentName.FirstOrDefault(); 
      model.StudentName = result.ToString(); 
     } 
    return View(model); 
} 

在得到以上,你可以在一个id传递,然后从数据库读取记录。使用检索到的数据填充模型属性,并将该模型传递到视图中。

然后在下面的发布操作中,您接受模型作为参数,检查模型状态并处理数据。我在此处显示重定向,但您可以在执行后执行后返回任何您想要的视图。

[HttpPost] 
public ActionResult StudentName(StudentModel model) 
{ 
    if(ModelState.IsValid) 
    { 
     using (var db = new SchoolDataContext()) 
     { 
      //update your db record 
     } 
     return RedirectToAction("Index"); 
    } 
    return View(model); 

} 
+0

我现在正在尝试这个,但我想知道(int studentId),我传入get - 它将获取id与数据库中的id进行比较? – 072et

+0

我的操作方法没有被击中,我不知道为什么 - 你可能会再次看看? – 072et

+0

@ 072et将'

相关问题