2011-01-13 157 views
15

在我的控制器的動作,我有以下代碼:如何在驗證集合asp.net mvc中添加驗證錯誤?

public ActionResult GridAction(string id) 
{ 
    if (String.IsNullOrEmpty(id)) 
    { 
     // add errors to the errors collection and then return the view saying that you cannot select the dropdownlist value with the "Please Select" option 
    } 

    return View(); 
} 

UPDATE:

if (String.IsNullOrEmpty(id)) 
{ 
    // add error 
    ModelState.AddModelError("GridActionDropDownList", "Please select an option"); 
    return RedirectToAction("Orders"); 
} 

更新2:

這是我更新的代碼:

@Html.DropDownListFor(x => x.SelectedGridAction, Model.GridActions,"Please Select") 
@Html.ValidationMessageFor(x => x.SelectedGridAction) 

模型廁所KS像下面這樣:

public class MyInvoicesViewModel 
{ 

    private List<SelectListItem> _gridActions; 

    public int CurrentGridAction { get; set; } 

    [Required(ErrorMessage = "Please select an option")] 
    public string SelectedGridAction { get; set; } 

    public List<SelectListItem> GridActions 
    { 
     get 
     { 
      _gridActions = new List<SelectListItem>(); 
      _gridActions.Add(new SelectListItem() { Text = "Export to Excel", Value = "1" }); 

      return _gridActions; 
     } 
    } 
} 

這裏是我的控制器操作:

public ActionResult GridAction(string id) 
{ 
    if (String.IsNullOrEmpty(id)) 
    { 
     // add error 
     ModelState.AddModelError("SelectedGridAction", "Please select an option"); 
     return RedirectToAction("Orders"); 
    } 

    return View(); 
} 

什麼也沒有發生!我完全失去了這一個!

更新3:

我現在用下面的代碼,但仍確認在不觸發:

public ActionResult GridAction(string id) 
{ 
    var myViewModel= new MyViewModel(); 
    myViewModel.SelectedGridAction = id; // id is passed as null   

    if (!ModelState.IsValid) 
    { 
     return View("Orders"); 
    } 

UPDATE 4:

$("#linkGridAction").click(function() { 
    alert('link grid action clicked'); 

    $.get('GridAction/', { SelectedGridAction: $("#SelectedGridAction").val() }, function (result) { 
     alert('success'); 
    }); 
}); 

和控制器看起來如下:

// OrderViewModel has a property called SelectedGridAction. 
public ActionResult GridAction(OrderViewModel orderViewModel) 
{ 
    return View(); 
} 

更新5:驗證器不點火:

public ActionResult GridAction(OrderViewModel orderViewModel) 
{ 
    if (!ModelState.IsValid) 
    { 
     return View("Orders", orderViewModel); 
    } 
    return View(); 
} 

回答

6

你可以使用一個視圖模型:

public class MyViewModel 
{ 
    [Required] 
    public string Id { get; set; } 
} 

然後:

public ActionResult GridAction(MyViewModel model) 
{ 
    if (ModelState.IsValid) 
    { 
     // the model is valid, the user has selected an id => use it 
     return RedirectToAction("Success"); 
    } 
    return View(); 
} 

UPDATE:

數百對我的回答評論我的必要性感到爲客戶提供全方位工作示例後:

像往常一樣開始了視圖模型:

public class MyViewModel 
{ 
    [Required] 
    public string SelectedItemId { get; set; } 

    public IEnumerable<SelectListItem> Items 
    { 
     get 
     { 
      // Dummy data 
      return new SelectList(Enumerable.Range(1, 10) 
       .Select(i => new SelectListItem 
       { 
        Value = i.ToString(), 
        Text = "item " + i 
       }), 
      "Value", "Text"); 
     } 
    } 
} 

然後控制器:

public class HomeController: Controller 
{ 
    public ActionResult Index() 
    { 
     return View(new MyViewModel()); 
    } 

    [HttpPost] 
    public ActionResult Index(MyViewModel model) 
    { 
     if (!ModelState.IsValid) 
     { 
      // The user didn't select any value => redisplay the form 
      return View(model); 
     } 
     // TODO: do something with model.SelectedItemId 
     return RedirectToAction("Success"); 
    } 
} 

最後的觀點:

<% using (Html.BeginForm()) { %> 
    <%= Html.DropDownListFor(
     x => x.SelectedItemId, 
     Model.Items, 
     "-- Select Item --" 
    ) %> 
    <%= Html.ValidationMessageFor(x => x.SelectedItemId) %> 
    <input type="submit" value="OK" /> 
<% } %> 
53

使用ModelState.AddModelError()

ModelState.AddModelError("MyDropDownListKey", "Please Select"); 

,並輸出到像這樣的觀點:

<%= Html.ValidationMessage("MyDropDownListKey") %> 
+4

+1直接和簡單的答案「用`ModelState.AddModelError()'」。 – 2014-05-28 19:39:51

+0

我從哪裏得到鑰匙?我ahve以下:`<跨度類= 「字段」> @ Html.EditorFor(型號=> model.ClientID,新的{htmlAttributes =新{@class = 「形式控制」}}) @ Html.ValidationMessageFor(模型=> model.ClientID 「」 新{@class = 「TEXT-危險」}) `什麼是關鍵? – Zapnologica 2014-08-15 10:31:08

0

關於你提到的更新#3,我懷疑那是因爲你實際上是分配,它只是一個空字符串(必需的檢查空)的值。

你想確實有這個:

[Required(AllowEmptyStrings = false)] 

你最好的選擇,雖然將執行自定義驗證(你可能會想驗證的關鍵是在列表等)

編輯:在代碼中固定的錯字 - 忘了關閉「)」