如何在验证集合ASP.NETMVC中添加验证错误?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (23)

在我的控制器的动作中,我有以下代码:

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(); 
}
if (String.IsNullOrEmpty(id))
{
    // add error 
    ModelState.AddModelError("GridActionDropDownList", "Please select an option");
    return RedirectToAction("Orders"); 
}

这是我更新的代码:

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

模型如下所示:

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(); 
}

什么都没发生!我完全失去了这一个!

我现在正在使用下面的代码,但仍然没有激发验证:

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

    if (!ModelState.IsValid)
    {
        return View("Orders");
    }
$("#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(); 
}

验证不会触发:

public ActionResult GridAction(OrderViewModel orderViewModel)
{
    if (!ModelState.IsValid)
    {
        return View("Orders", orderViewModel); 
    }
    return View(); 
}
提问于
用户回答回答于

可以使用视图模型:

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();
}

一个完整的实例:

像往常一样从视图模型开始:

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" />
<% } %>
用户回答回答于

使用 ModelState.AddModelError()

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

并输出到这样的视图:

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

扫码关注云+社区