Shayan
Shayan

Reputation: 402

Remote validation in 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;

And in my Controller:

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

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?

Upvotes: 0

Views: 678

Answers (2)

J. Holmes
J. Holmes

Reputation: 18546

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:

To your ViewModel add:

public bool IsEditing { get; set; }

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

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.

Upvotes: 1

Adam Tuliper
Adam Tuliper

Reputation: 30152

Use two view models, each has a different property name with its applicable remote validation method. This is yet another of the many reasons to simply use view models for each view. So you should have a view model for Create and for Edit.

Upvotes: 1

Related Questions