我正在听一个提交我的一个观点的表单,它正在检查记录。我想要做的是,是否有记录允许表单实际呈现视图,如果不是只显示错误页面。显然,继续代码的“其他”假设它是空的..有关如何实现这一点的任何想法?
这是实际拦截并发布到AJAX的JS函数。
$('form#search-form').submit(function (evt) {
$.ajax({
type: 'POST',
url: '<%: Url.Action("Details","SpecialtyTrack") %>',
data: $(this).serialize(),
success: function (response) {
if (response.results == 0) {
$('#error').fadeOut('fast');
$("#error").fadeIn('slow');
}
else {
$('#error').hide();
};
},
error: function (response) {
alert(response);
}
});
evt.preventDefault();
});
这是我的控制器代码:
public ActionResult Details(string searchParameter)
{
var sP = this.spRepo.findSpecialtyTrack(searchParameter);
try
{
var record = sP.FirstOrDefault();
ViewData["directoryID"] = record.DirectoryArtItem.DirectoryCanvass.DirectoryEdition.DirectoryID;
ViewData["directoryName"] = record.DirectoryArtItem.DirectoryCanvass.DirectoryEdition.Directory.Name;
return View(sP);
}
catch (NullReferenceException)
{
return Json(new {
results = 0
});
}
}
答案 0 :(得分:1)
在catch中设置Response.StatusCode = 500,它将在jQuery的ajax调用中触发错误回调。然后,您可以根据需要处理错误。
public ActionResult Details(string searchParameter)
{
var sP = this.spRepo.findSpecialtyTrack(searchParameter);
try
{
var record = sP.FirstOrDefault();
ViewData["directoryID"] = record.DirectoryArtItem.DirectoryCanvass.DirectoryEdition.DirectoryID;
ViewData["directoryName"] = record.DirectoryArtItem.DirectoryCanvass.DirectoryEdition.Directory.Name;
return View(sP);
}
catch (NullReferenceException)
{
Response.StatusCode = 500;
return Json(new {
results = 0
});
}
}
答案 1 :(得分:0)
我会把它解决为2个动作 一个作为验证部分/另一个作为ajax请求,如果它必须是
<% using Ajax.BeginForm("ValidateAction",new AjaxOptions{ UpdateId="HolderWhereSubmitButtonWillBe"}){
%>
validation page
<%}%>
您的ValidateAction的响应作为部分视图返回
<div id="HolderWhereSubmitButtonWillBe">
here will be the ajax call code and button to submit via ajax(all as partail view send as reponse for validation
</div>
我还会添加类似
的内容if(!modelstate.isvalid)返回view()
只是为了确保