0

学生のテーブルがあり、学生のテーブルに保存されているプロファイルページに学生の名前を表示したいと思いました。

これは私が私のコントローラーのために心に留めていることです:

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メソッドを使用して、[保存]をクリックした後に同じボックス内で変更した場合に保存できるようにします。

4

1 に答える 1

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);
}

上記の get では、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);

}
于 2013-02-06T19:46:52.030 に答える