2011-01-13 134 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)] 

你最好的选择,虽然将执行自定义验证(你可能会想验证的关键是在列表等)

编辑:在代码中固定的错字 - 忘了关闭“)”