2016-03-21 27 views
3

MVCにモデルとアクションメソッドがあります。編集時のASP.NET MVCリモート検証ロジック

public class employee 
{ 
    [Key] 
    public int id { get; set; } 

    [Required] 
    public string employeeID { get; set; } 

    [Required] 
    [Remote("doesCnicExist", "employee", AdditionalFields = "employeeID", HttpMethod = "POST", ErrorMessage = "A user with this cnic already exists. Please enter a different cnic.")] 
    public string cnic { get; set; } 
} 

[HttpPost] 
    public JsonResult doesCnicExist(string employeeID, string cnic) 
    { 
     var empList = hc.employee.ToList(); 
     bool flag = false; 
     foreach (employee e in empList) 
     { 
      if ((employeeID == e.employeeID) && (cnic == e.cnic)) 
      { 
       flag = true; 
      } 
     } 
     return Json(flag == false); 
    } 

Create()アクションでは、それは素晴らしい動作します。しかし、Edit()アクションでは、プログラムはすでにcnicが存在するとみなします。そして、employeeを同じcnicで更新することはできません。私は追加のemployeeIDフィールドを使用して、編集中に従業員オブジェクトの一意性をどのように得ることができるのか分かりませんか?

+0

'int id'と' string employeeID'の違いは何ですか?そして、あなたが試した 'doesCnicExist()'メソッドを表示する必要があります。 –

+0

@StephenMuecke 'int id'はテーブルのデータベースによって自動生成され、' Employee ID'は組織によって割り当てられます。申し訳ありませんが、私はこの状況のた​​めに考えられる論理について、 'doesCnicExist()'について全く考えることができませんでした。だから私はこの質問をしました。 – Jogi

+0

しかし、それはあなたの 'Create()'アクションのために働くと言いました。それを表示して、 'Edit()'メソッドのために修正することができます。 ( 'id'と' employeeID'フィールドまでは2つの識別子フィールドがありますが、それは 'AdditionalFields'の' id'フィールドを使うべきです) –

答えて

1

idは一意の識別子なので、doesCnicExist()メソッドに渡す必要があります。そして、idが既に存在する行を無視するようにロジックを変更できます。 RemoteAttributeのみクライアント側の検証で、検証が常にサーバー上で実行する必要がありますので、私は別のメソッドにロジックを分離している

[HttpPost] 
public JsonResult doesCnicExist(string cnic, int id) 
{ 
    return Json(IsUnique(cnic, id)); 
} 

private bool IsUnique(string cnic, int id) 
{ 
    if (id == 0) // its a new object 
    { 
    return !hc.employee.Any(x => x.cnic == cnic); 
    } 
    else // its an existing object so exclude existing objects with the id 
    { 
    return !hc.employee.Any(x => x.cnic == cnic && x.id != id); 
    } 
} 

ノートに

public class employee 
{ 
    [Key] 
    public int id { get; set; } 
    .... 
    [Required] 
    [Remote("doesCnicExist", "employee", AdditionalFields = "id", HttpMethod = "POST", ErrorMessage = "A user with this cnic already exists. Please enter a different cnic.")] 
    public string cnic { get; set; } 
} 

とコントローラメソッドにモデルを変更(クライアント側の検証は素晴らしいボーナスだと考えられますが、悪意のあるユーザーは簡単にそれをバイパスできます)。別の方法では、Create()Edit()のPOSTメソッドでその妥当性を検証し、データベースに保存する際にスローされる可能性のある例外を防ぐこともできます。

RemoteAttributeはクライアント側(UI)属性なので、データモデルには適用しないでください。view modelのビューモデルプロパティに適用されているベストプラクティスに従ってください。データモデルクラスとプロパティ名(つまりPascalCase)には通常の命名規則を使用することをおすすめします。

+0

サイドノート:どのように動作するかの例は、[this DotNetFiddle](https://dotnetfiddle.net/jVHK7p)を参照してください。 –

+0

あなたの提案した解決策の後、申し訳ありませんが、 '[HttpPost] Create()'は起動しません。 「作成」ボタンを押すと、そこでプログラムがジャムするだけです。 – Jogi

+0

私のコードの中には、あなたの 'Create()'メソッドと何も関係がありません。あなたの質問にそれを表示していません。 –

関連する問題