我想出了一个场景,我得到了多个问题,并且选项MCQ使用单个ID我想在部分视图上显示随机问题,当用户点击下一个按钮时,它应该使用MVC EF加载另一个随机问题。这是我的代码。
var modeldata =
Db.ExamQuestions.Include("ListofOptions").Where(x => x.FkExamId == model.ExamId).Select(q => new QuestionViewModel
{
QuestionId = q.ID,
QuestionDescription = q.QuestionDescription,
ExamId = q.FkExamId,
CorrectOption = q.CorrectOption,
ListofOption = q.ListofOptions.Select(o => new QuestionOptionViewModel
{
OptionA = o.OptionA,
OptionB = o.OptionB,
OptionC = o.OptionC,
OptionD = o.OptionD
}).ToList()
}).OrderBy(q => q.QuestionId).Take(1).ToList();
答案 0 :(得分:0)
如果您要显示不同订单的数据。在viewModel的每条记录上设置一个随机数,并将viewModel传递给View。
public ActionResult Random()
{
int maxCnt = 5; //The max number of questions for user
ViewBag.QsIds = (new TmsDbContext()).Database
.SqlQuery<MyQuestion>($"SELECT TOP {maxCnt} * FROM MyQuestions ORDER BY NEWID()")
.Select(x=> x.Id).ToList();
return View();
}
[HttpGet]
[Route("GetPartailView/{id}")]
public ActionResult GetPartialView(int id)
{
var viewModel = (new DbContext()).MyQuestions.Find(id);
return PartialView("~/Views/Home/_PartialView.cshtml", viewModel);
}
控制器:从数据库中获取随机问题的id列表,并创建另一个用于返回_PartialView的HttpGet方法。
@model MyQuestion
<span>@Model.Title</span>
_PartialView:显示问题
<input type="button" value="Next" id="next"/>
<div id="qsDiv"></div>
<script>
$(function (){
var qsIds = [];
var array = @Html.Raw(Json.Encode(@ViewBag.QsIds));
for(var i = 0; i < array.length; i++) {
qsIds[i] = array[i];
}
var getPartialViewUrl = "/Home/GetPartialView/";
var index = 0;
$("#next").click(function () {
$.ajax({
dataType: "html",
url: getPartialViewUrl + qsIds[index],
success: function (html) {
$("#qsDiv").html("");
$("#qsDiv").append(html);
index++;
}
})
})
});
</script>
查看:Ajax并呈现当前问题的_PartialView
accessToken=AccessToken.getCurrentAccessToken();
if(accessToken==null)
{
Intent intent = new Intent(getApplicationContext(),LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
return;
}
String fbUserId=Profile.getCurrentProfile().getId();
try {
new GraphRequest(
accessToken,
"/"+fbUserId+"/live_videos",
null,
HttpMethod.POST,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.v("0",response.getRawResponse());
}
}
).executeAsync();
} catch (Exception e) {
e.printStackTrace();
}