首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在验证集合asp.net mvc中添加验证错误?

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

Stack Overflow用户
提问于 2011-01-13 22:47:40
回答 3查看 50.7K关注 0票数 18

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

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

更新2:

下面是我更新的代码:

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

什么都没发生!我对这件事完全迷惑了!

更新3:

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

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

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

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

回答 3

Stack Overflow用户

回答已采纳

发布于 2011-01-13 22:52:03

您可以使用视图模型:

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" />
<% } %>
票数 7
EN

Stack Overflow用户

发布于 2011-01-13 22:49:25

使用ModelState.AddModelError()

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

并输出到视图,如下所示:

<%= Html.ValidationMessage("MyDropDownListKey") %>
票数 61
EN

Stack Overflow用户

发布于 2011-01-13 23:49:48

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

你想要这样做:

[Required(AllowEmptyStrings = false)]

不过,您最好的方法是执行自定义验证(您可能希望验证密钥是否在列表中,等等)

编辑:修复代码中的拼写错误-忘记结束")“

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4681328

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档