Oleksii Kryzh Oleksii Kryzh - 3 months ago 8
ASP.NET (C#) Question

Different validating actions in ASP.NET MVC Application

I am trying to implement simple CMS. I have

Page
class instances of which I want to add to the database and also to edit them.
The
UrlName
in the
Page
should be unique so I made custom validator, though, while editing I cannot submit form without changing
UrlName
to an unexisting one. How can I pass extra data to my
VerifyUrl
or maybe there is another way to solve this problem?

public class Page : IUpdatable<Page>
{
public int ID { get; set; }
[Required]
[DataType(DataType.Url)]
[Remote(action: "VerifyUrl", controller: "Pages")]
public string UrlName { get; set; }
}


This is my validating method in
PagesController


public JsonResult VerifyUrl(string UrlName)
{
if (!db.Pages.Any(x => x.UrlName.Equals(UrlName)) )
return Json(data: true);
return Json(data: "This Url is already in use");
}


And this is in my View

<input asp-for="UrlName" class="form-control" />
<span asp-validation-for="UrlName" class="text-danger" />

Answer

Specify 'This URL is already in use' in Remote ErrorMessage and in your Action Mehtod, return false in Json if provided URL is already is Use.

Model class

[DisplayName("URL")]
   [Required]
   [Remote("Validate", "Home", HttpMethod = "Post", ErrorMessage = "This URL already exists")]
   public string URL { get; set; }

In your controller

   [HttpPost]
    public ActionResult Validate(string URL)
    {
       //Do validation here from DataBas
        //if URL already exist, return false, else true;

            return Json(false);

    }

Working Demo

To pass additional information to your controller method, you can specify an Additional Field in Remote Attribute as:

     [DisplayName("User name")]
     [Required]
      public string UserName { get; set; }

      [DisplayName("URL")]
      [Required]
      [Remote("Validate", "Home", HttpMethod = "Post",AdditionalFields="UserName", ErrorMessage = "This URL and Username should not be same")]
     public string URL { get; set; }


 [HttpPost]
    public ActionResult Validate(string URL, string UserName)
    {
        if(URL == UserName)
            return Json(false);
        else
            return Json(true);

    }

Woking Demo for additional field

Comments