Remote Attribute Validation Fails in Asp.Net MVC

Here is my model code

public class BlobAppModel
{
   [Required(ErrorMessage="Please enter the name of the image")]
   [Remote("IsNameAvailable","Home",ErrorMessage="Name Already Exists")]
   public string Name { set; get; }           
}

And in my controller I have

public JsonResult IsNameAvailable(string Name)
{
   bool xx= BlobManager.IsNameAvailable(Name);
   if (!xx)
   {
      return Json("The name already exists", JsonRequestBehavior.AllowGet);
   }
   return Json(true, JsonRequestBehavior.AllowGet);
}

And in my data I

public static bool IsNameAvailable(string Name)
{
   var test = "";
   using (var x = new BlobTestAppDBEntities())
   {
       try
       {
            test=x.BlobApps.Where(m => m.Name == Name).FirstOrDefault().Uri;
            if (test != null)
               return false;
            else
               return true;
       }
       catch (Exception)
       {
          return true;
       }
   }
}

In my opinion, I added scripts too

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {

    <td> @Html.Label("Name:") 
                 @Html.TextBoxFor(m => m.Name)
                 @Html.ValidationMessageFor(m=>m.Name)</td>}

But remote verification does not work at all. Are there any problems with my code?

+4
source share
4 answers

Make sure your validation method is decorated with the [AllowAnonymous] attribute ([HttpPost] may also be required).

[AllowAnonymous]
public JsonResult IsNameAvailable(string Name)

Also tip: use browser developer tools (F12 button in major browsers) to view Json request status.

+10
source

jquery.unobtrusive-ajax.js , , .

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

, nuget

nuget link http://www.nuget.org/packages/Microsoft.jQuery.Unobtrusive.Ajax/

+4

I know this is a little late. If you use Razor syntax, I found that in addition to everything you did, you also need:

@Scripts.Render("~/bundles/jqueryval")
+1
source

These parameters must also be run in web.config:

<appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
0
source

All Articles