asp.net-mvc 如何在验证集合asp.net mvc中添加验证错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4681328/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:42:59  来源:igfitidea点击:

How to add validation errors in the validation collection asp.net mvc?

asp.net-mvcasp.net-mvc-3

提问by johndoe

Inside my controller's action I have the following code:

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

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

UPDATE 2:

更新 2:

Here is my updated code:

这是我更新的代码:

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

The Model looks like the following:

该模型如下所示:

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

And here is my controller action:

这是我的控制器操作:

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

    return View(); 
}

Nothing happens! I am totally lost on this one!

没发生什么事!我完全迷失在这一点上!

UPDATE 3:

更新 3:

I am now using the following code but still the validation is not firing:

我现在使用以下代码,但验证仍未触发:

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:

更新 4:

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

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

And the Controller looks like the following:

控制器如下所示:

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

UPDATE 5: Validation is not firing:

更新 5:验证未触发:

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

采纳答案by Darin Dimitrov

You could use a view model:

您可以使用视图模型:

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

and then:

进而:

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:

更新:

After the hundreds of comments on my answer I feel in the necessity to provide a full working example:

在对我的答案发表数百条评论后,我觉得有必要提供一个完整的工作示例:

As usual start with a view model:

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

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

Then a controller:

然后是一个控制器:

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

and finally the view:

最后是视图:

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

回答by hunter

Use ModelState.AddModelError()

ModelState.AddModelError()

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

and output to the view like this:

并输出到这样的视图:

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

回答by Chance

Regarding your update #3, I suspect thats because you are actually assigning the value, its just an empty string (Required is checking for null).

关于您的更新 #3,我怀疑那是因为您实际上是在分配值,它只是一个空字符串(需要检查是否为空)。

You want to do have this:

你想要这样做:

[Required(AllowEmptyStrings = false)]

Your best bet though would be to perform custom validation (you will likely want to verify the key is in the list, etc)

您最好的选择是执行自定义验证(您可能希望验证密钥是否在列表中等)

Edit: fixed typo in the code - forgot closing ")"

编辑:修复了代码中的错字 - 忘记关闭“)”