2011-07-22 5 views
0

コントローラアクションでStudentIdがパラメータとして渡されるとき、渡されたIDがコントローラアクション内のStudentTableに存在するかどうかを検証するにはどうすればよいですか?Validateはコントローラアクション内のStudentTableに存在するStudentIDです

 public ActionResult LookUpStudentId(string id) 
    { 

     if(id != //not present in StudentTable) 
      return new RedirectResult("~/Error/NotFound"); 


     return View(); 

    } 

答えて

3

質問に対する回答は、SQLサーバーにアクセスするために使用しているデータアクセス技術に大きく依存します。その後、

public bool IsStudentExists(string id) 
{ 
    using (var conn = new SqlConnection("some connection string")) 
    using (var cmd = conn.CreateCommand()) 
    { 
     conn.Open(); 
     cmd.CommandText = "SELECT id FROM StudentTable WHERE id = @id"; 
     cmd.Parameters.AddWithValue("@id", id); 
     using (var reader = cmd.ExecuteReader()) 
     { 
      return reader.Read(); 
     } 
    } 
} 

と::

public ActionResult LookUpStudentId(string id) 
{ 
    if(!IsStudentExists(id)) 
    { 
     return new RedirectResult("~/Error/NotFound"); 
    } 
    return View(); 
} 

明らかに、このデータ・アクセス・コードをリポジトリにリファクタリングすることが優れている、あなたはそれについて私たちに語っていないので、ここで、この使用して、プレーンADO.NETを達成する方法を説明しますコントローラが使用しているデータアクセステクノロジに密接に結合されていないようにします。たとえば、あなたが定義してIStudentsRepository

public class StudentsController: Controller 
{ 
    private readonly IStudentsRepository _repository; 
    public StudentsController(IStudentsRepository repository) 
    { 
     _repository = repository; 
    } 

    public ActionResult LookUpStudentId(string id) 
    { 
     var student = _repository.GetStudent(id); 
     if(student == null) 
     { 
      return new RedirectResult("~/Error/NotFound"); 
     } 
     return View(student); 
    } 
} 

すべてのこと残されているがconfigure your DI framework of choiceに適切に注入する:あなたは、その後実装し、今お使いのコントローラのアクションは、この抽象化して仕事ができる

public interface IStudentsRepository 
{ 
    Student GetStudent(string id); 
} 

このリポジトリのコントローラへの実装

+0

Entity Framework – user793468

+0

@ user793468を使用しています。これは、EntityFrameworkを使用して示した「IStudentsRepository」を実装するだけです。例えば、あなたがIDを与えられたEFモデルを直接返す 'StudentsRepositoryEF'を持つことができます。 –

0

は私のIntro MVC 3チュートリアル

// GET: /Movies/Delete/5 

公共のActionResult削除(int型のID = 0){ 作品の映画= db.Movies.Find(ID)のlast pageを参照してください。 if(movie == null) { return HttpNotFound(); } 戻る表示(ムービー); }

関連する問題