我试图检查模型是否为空,但我无法解决这个问题。在呈现主视图时,我将部分视图呈现如下
主视图
<div class="modal fade" id="surveyPreviewModal" data-backdrop="static" data-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="surveyPreviewLabel" aria-hidden="true">
<div class="modal-lg modal-dialog">
<div class="modal-content" id="surveyPreviewContent">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
×
</button>
<h4 class="modal-title" id="surveyPreviewLabel">Survey Preview</h4>
</div>
<div class="modal-body" id="surveyPreviewBody">
@Html.Partial("_surveyPreview")
</div>
</div>
</div>
</div>
在部分视图中,我的功能如下
@model LMS_TraineeSurveyPaginationViewModel
<script type="text/javascript">
function SurveyPreview(){
var surveyQuestionViewModel = @Html.Raw(Json.Serialize(Model.SurveyQuestionsViewModel.ToArray()));
var surveyQuestionOptionChoideViewModel= @Html.Raw(Json.Serialize(Model.SurveyQuestionOptionChoiceViewModel.ToArray()));
$.post('@Url.Action("SurveyPreview", "Survey")', { SurveyID : surveyID,` page : page },
function (data) {
$('#surveyPreviewBody').html('');
$('#surveyPreviewBody').html(data);
SetProgressBar(page,'@(Model==null?0: Model.Pager.TotalPages)');
}).fail(function () {
alert("error in GetTraineeSurvey");
}).success(function () {
});
}
</script>
因此,在呈现此函数(SurveyPreview)中的部分视图时,当模型为null时,它会给出错误,并立即显示白色屏幕。如果我没有调用部分视图中的函数,那么它为什么要检查模型是否为空?它应该是每当我执行功能,如按一下按钮?
在显示引导模式的主视图上有一个按钮,在引导模式的'show
‘方法上,我再次返回相同的部分视图,以绑定ajax调用中的数据。下面的代码是用部分视图编写的
$(document).ready(function () {
$('#surveyPreviewModal').on('show.bs.modal', function (e) {
surveyID = $(e.relatedTarget).attr('data-surveyID');
SurveyPreview(@SurveyPageTypePageNumber.StartPage,null);
});
})
在控制器中
public ActionResult SurveyPreview(int SurveyID, int page)
{
------ some code ------
return PartialView("_SurveyPreview",viewModel);
}
对此有任何帮助,非常感谢!
发布于 2017-02-17 06:57:45
使用@Html.Partial("_surveyPreview")加载部分视图时,需要传递未提供的LMS_TraineeSurveyPaginationViewModel
因此,要调用部分视图,您需要编写以下内容
@Html.Partial("_surveyPreview",new LMS_TraineeSurveyPaginationViewModel());
发布于 2017-02-17 07:08:36
部分视图需要一个类型为LMS_TraineeSurveyPaginationViewModel
的模型。但是,在从主视图呈现部分视图时,不传递任何模型对象。
在partialview中,function SurveyPreview()
使用模型的属性。由于您没有从主视图中传递任何模型对象,因此model在部分视图中将为null。这就是你看到NullReferenceException
的原因。
因此,您需要确保部分视图得到模型。
您需要采取不同的方法来呈现部分视图。您可以使用Html.Action
调用Action方法,该方法将返回部分视图并在主视图中呈现。
替换主视图中的以下行
@Html.Partial("_surveyPreview")
使用
@Html.Action("SurveyPreview", new { SurveyID = "<<somesoveryId>>", page = "<<somepage>>"})
这样,我将用提供的参数调用控制器的SurveyPreview
操作,它将返回带有模型的部分视图,并将其呈现出来。
我不确定要在SurveyID
和page
参数中传递哪些值,所以我在那里放置了占位符。你需要把适当的值放在那里。
https://stackoverflow.com/questions/42298698
复制