2015-08-30 86 views
0

我在使用ASP.NET Web頁面的實體框架(Razor 3)。我準備好了驗證代碼,我使用Entity Frameworks自己的驗證過程。但是有一個問題,例如在我的模型和數據庫中有一個名爲的小數字段。我用的是這樣的:實體框架中的數據驗證

Item.Amount = decimal.Parse(Request.Form["ItemAmount"]); 

這裏的問題是,如果輸入的非數字,我得到一個錯誤(顯然)。我可以很容易地通過檢查輸入是否是數字來修復它,但如果我這樣做,那麼驗證檢查的方式就太多了。我的意思是,我檢查它是否是代碼中的數字,然後Entity Framework再次檢查值,所以我使用了兩個不同的驗證過程,這對我來說似乎不好。

Ofcourse還有一個客戶端,也許我可以使用數字只有文本框,但我不知道。

任何想法?

下面是完整的代碼,它可能是太可怕了,我是相當新的實體框架(如3-4天):

if (IsPost) 
{ 
    try 
    { 
     Worker curWorker = new Worker(); 
     try 
     { 
      curWorker = m.Workers.Find(decimal.Parse(Request.Form["WorkerId"])); 
     } 
     catch (Exception) 
     { 
      errors += "Lütfen bir personel seçin. <br />"; 
     } 

     overhour.Worker = curWorker; 
     overhour.PhaseId = curPhase.PhaseId; 

     try 
     { 
      overhour.OverhourAmount = decimal.Parse(Request.Form["OverhourAmount"]); 
     } 
     catch (Exception) 
     { 
      errors += "Süre (Saat) alanı sayısal olmalıdır. <br />"; 
     } 

     overhour.OverhourDate = DateTime.Today; 

     curWorker.Overhours.Add(overhour); 

     Accounting accounting = new Accounting(); 
     accounting.AccountingMethod = 0; 
     accounting.AccountingNote = curWorker.WorkerFullName + " adlı personelin, " + overhour.OverhourAmount + " saat süreli, " + DateTime.Today.ToShortDateString() + " tarihli mesai kaydı."; 
     accounting.AccountingType = 3; // Maaş 
     accounting.AccountingBorc = 0; 
     accounting.AccountingAlacak = curWorker.WorkerOverWorkSalary * overhour.OverhourAmount; 

     accounting.Phases = curPhase; 

     curWorker.Accountings.Add(accounting); 

     if (errors != "") 
     { 
      throw new WrongValueException(errors); 
     } 

     m.SaveChanges(); 
     Response.Redirect(Page.ParentPage); 
    } 
    catch (DbEntityValidationException ex) 
    { 
     errors = kStatic.getValidationErrors(ex.EntityValidationErrors, "<br />"); 
    } 
    catch (WrongValueException ex) 
    { 
     errors = ex.Message.ToString(); 
    } 
    catch (Exception ex) 
    { 
     errors = "Bilinmeyen hata, teknik detaylar: " + ex.Message; 
    } 
} 
+0

改爲使用模型綁定 - 當您可以讓Post事件接受複雜的數據類型並讓MVC執行綁定和驗證時,爲什麼要查詢'Request.Form'。然後,你可以檢查'Model.IsValid' –

+0

@BrendanGreen我沒有實際使用MVC,我試過了,最糟糕的問題是綁定了我,我不知道爲什麼。 – user5273382

+0

請顯示整個發佈操作。 –

回答

0

我會做的是使一個擴展方法,例如像這兩個。

public static decimal AsDecimal(this string value) 
{ 
    decimal result; 
    return decimal.TryParse(value, out result) ? result : 0; 
} 

public static decimal? AsNullableDecimal(this string value) 
{ 

    decimal result; 
    bool IsValid = decimal.TryParse(value, out result); 

    if (IsValid) 
    { 
     return result; 
    } 
    else 
    { 
     return null; 
    } 

} 

然後簡單地檢查像這樣的小數值。

decimal? value = Request.Form["WorkerId"].ToString().AsDecimal() 

if (value.HasValue) //AsDecimal is overloaded you can make it return 0 if you wish 
//dome something 
else 
//do something. 

我認爲這應該指向正確的方向。同樣在該筆記上,CLIENT驗證是不好的,用戶總是可以使用開發工具等工具來改變它。不要依賴客戶端驗證。