In my MVC view screen, on click of button, i do ajax call through $.ajax and it able to call controller's action method and return the reponse into success event.
controller action method's return type is JsonResult and returning Json(object,AllowGEt)
I have included jquery file and validation file in _layout file.
Problem: Problem is unable to fire validation on client side.
I have already included - Required annotaion and error message annotation on model object.
Please guide me what is wrong.
(it was working fine while doing validation inside BeginForm and button as Submit button and call to action method having return type as ActionResult but, no ajax call.)
Modified to include code:
On View on button click event :
<script type="text/javascript">
$("#btnJsonSubmit").click(function () {
var f = JSON.stringify(
{ 'IDValue': objIDValue };
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: '/cPreferences/InsertPreference',
data: f,
success: function () {
alert('Record saved successfully.');
$('select').prop('selectedIndex', 0);
},
failure: function (response) {
alert('f');
//console.log('error!!');
}
});
});
</script>
On Controller's actio method:
[HttpPost]
public JsonResult InsertPreference(string IDValue)
{
///code to call services
return Json(l, JsonRequestBehavior.AllowGet);
}
View Model object
View MOdel
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace ViewModel
{
public class CampusProgramPreferencesViewModel
{
[Required(ErrorMessage = "Selection is required")]
public IList<LookupItem> DataList { get; set; }
[Required(ErrorMessage = "Preference is required")]
public string Preference { get; set; }
}
}
Layout_cshtml
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>