在MVC3.0远程验证 [英] Remote validation in MVC3.0

查看:133
本文介绍了在MVC3.0远程验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个远程验证一类的领域之一:

I have a remote validation on one of the fields of a class:

    [Remote("IsCityUnique", "City", AdditionalFields = "Onvan", HttpMethod = "POST", ErrorMessage = "City name isn't unique.")]
    public string CityName
    {
        get { return _CityName; }
        set
        {
            if (_CityName != value)
            {
                _CityName = value;
                OnPropertyChanged("CityName");
            }
        }
    }
    private string _CityName;

在我的控制器:

    public JsonResult IsCityUnique(string Cityname)
    {
        ....
        List<City> citylist = cr.GetAll().ToList();
        return Json(!citylist .Any(c => c.CityName== Cityname));
    }

在IsCityUnique将正确触发,但在编辑和放大器验证方法;创建是我diffrent.How可以开火时,我在创建模式或编辑模式适当的方法?我想,如果我可以通过操作名称这个方法那么我可以管理它。但是我不知道我怎么能传递动作名称远程method.Otherwise,你可以建议我一个正确的方法是什么?

the "IsCityUnique" will fire correctly , but validation method in Edit & Create is diffrent.How can I fire proper method when I'm in create mode or Edit mode? I think if I can pass action name to this method then I can manage it.But I didn't know how can I pass action name to remote method.Otherwise , can you suggest me a proper way?

推荐答案

因此​​,虽然我还是会建议使用独立的视图模型进行编辑和创建,这已经不仅仅是远程验证的详细架构优势,你的的能够做到你想要使用 AdditionalFields 属性,你似乎可以用在房地产,但不是在你的验证处理程序是什么。

So while I would still recommend using separate ViewModel for edit and create, which has more architectural advantages than just remote validation, you should be able to do what you want using the AdditionalFields property, which you seem to be using in the property but not on your validation handler.

我不是在一个位置测试,但如果你的真正的想做的事是这样,那么你也许可以做到这一点如下:

I'm not in a position to test this, but if you really wanted to do it this way, then you might be able to do this following:

要您的视图模型添加:

public bool IsEditing { get; set; }

当你在此设置为true(假你的创作操作)的编辑操作。

When you are on your editing action set this to true (and false on your creation action).

[Remote("IsCityUnique", "City", AdditionalFields = "IsEditing", HttpMethod = "POST", ErrorMessage = "City name isn't unique.")]
public string CityName { get; set; }

在你看来,你可能有渲染 @ Html.HiddenFor(M = GT; m.IsEditing),然后你的验证处理程序应该变成:

In your view, you may have to render @Html.HiddenFor(m=>m.IsEditing), and then your validation handler should become:

public JsonResult IsCityUnique(string Cityname, bool IsEditing)
{
    if(editing) { /* Do editing Logic */ }
    else { /* Do other logic. */ }
}

像这样的的工作,但我不是在位置,现在测试它。但是,你真的可能是观察的关注点分离的更好,弄清楚如何编辑和创建一个域对象之间划分责任。

Something like this should work, but I'm not in the position to test it right now. But you would really probably be better of observing a separation of concerns and figure out how to divide the responsibilities between editing and creating a domain object.

这篇关于在MVC3.0远程验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆