我的控制器返回JsonResult,我根本不想使用Razor视图,我希望使用JQuery AJAX的简单Html页面向Controller操作发出请求。我能够做到这一切,但我希望JQuery使用Jquery unobtrusive验证我的模态(让我们说顺序创建[表单验证]),以便我可以显示Dataannotation属性错误消息而不是客户端验证错误。
请参阅下面的代码
我的控制器代码在
下面 [HttpPost]
public JsonResult SaveMovies(Movie movie)
{
AjaxResponse response = new AjaxResponse { Success = false };
try
{
_movieRepository.Add(movie);
_movieRepository.Save();
response.Data = "Movie added";
response.Success = true;
}
catch (Exception ex)
{
response.Success = false;
response.Message = "An exception occur while fetching data" + Environment.NewLine + "Method: " + ex.TargetSite + Environment.NewLine + "Source: " + ex.Source + Environment.NewLine + "Message: " + ex.Message;
MoviesLogger logger = new MoviesLogger();
logger.Error(ex);
}
return Json(response, JsonRequestBehavior.AllowGet);
}
我的Jquery代码如下
$("#save").click(function () {
var movie = {
Title: $('#TitleTextBox').val(),
ReleaseDate: $('#ReleaseDateTextBox').val(),
Genre: $('#GenreTextBox').val(),
};
if (isValid(movie)) {
SendRequest("Movies", "SaveMovies", JSON.stringify(movie), "post", function (response) { // AJAX Success
$("#Notification").html("Movie Added");
}, function (response) { // AJAX Fail
alert("Fail");
alert(response.Message);
});
}
else {
$('#errorDiv').html(""); // THIS DIV WILL LIST ALL THE error messages FROM MY POCO CLASS DataAnnotations Attributes
}
});
函数isValid Code在
下面 function isValid(Movie) {
try {
/*
I WANT TO VALIDATE THE POCO MODAL(Movie) AGAINST ALL DataAnnotations Attributes set in there
MY Movie POCO is as under
public class Movie
{
[Key]
public int ID { get; set; }
[StringLength(20)]
[Required(ErrorMessage="Title is required")]
public string Title { get; set; }
public DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
}
*/
return true;
} catch (e) {
return false;
}
}
功能SendRequest代码在
下面 function SendRequest(controller, action, data, type, onSuccess, onError) {
if (type.toLowerCase() == 'post')
data = JSON.stringify(data);
$.ajax({
url: baseUrl + '/' + controller + '/' + action,
dataType: 'json',
type: type,
data: data,
contentType: "application/json; charset=utf-8",
success: onSuccess,
error: onError
});