Remote Attribue Validation not firing in Asp.Net MVC

一笑奈何 提交于 2019-12-19 03:21:48

问题


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 have

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 view I have added the 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 validation is not firing at all..Is there any problem with my code?


回答1:


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

[AllowAnonymous]
public JsonResult IsNameAvailable(string Name)

Also a tip: use browser's developer tools (F12 button in major browsers) to see the status of Json request.




回答2:


you are missing the jquery.unobtrusive-ajax.js file in your view please add that and try it again.

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

if you don't have it get in from the nuget

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




回答3:


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

@Scripts.Render("~/bundles/jqueryval")



回答4:


These settings need to go in web.config too:

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


来源:https://stackoverflow.com/questions/19680967/remote-attribue-validation-not-firing-in-asp-net-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!