在ASP Razor View中没有调用Jquery函数

时间:2017-03-18 23:42:08

标签: jquery asp.net asp.net-mvc razor

我是MVC世界的新手,我正在尝试通过调用控制器操作方法进行ajax调用以从数据库获取json数据,每次运行应用程序时,数据都显示为视图上的原始JSON数据而不是根据我的jquery代码进行渲染。你能帮我指导我在这里做错了吗?

My Controller:

[HttpGet]
[ActionName("Question")]
public ActionResult GetQuestionPost()
{
    QuestionDefViewModel quesDef = new QuestionDefViewModel();
    OnlineExamEntities db = new OnlineExamEntities();
    quesDef.questionText = db.Questions.Where(z => z.questionId == 1000).Select(z => z.questionText).SingleOrDefault();

    var query = (from p in db.Choices
                 where p.questionId == 1000
                 select new
                 {
                     choiceId = p.choiceId,
                     choiceText = p.choiceText,
                     isCorrect = p.isCorrect
                 }).ToList();

    quesDef.Choices = query.Select(x => new Choice
    {
        choiceId = x.choiceId,
        choiceText = x.choiceText,
        isCorrect = x.isCorrect
    }).ToList();
    return Json(quesDef, JsonRequestBehavior.AllowGet);
}

我的观点:

@model ExamPortal.ViewModels.QuestionDefViewModel
....
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
    $(window).load(function () {
        debugger;
        alert("hi");
        function question() {
            $.ajax({
                url: '/Home/Question',
                type: 'Post',
                cache: false,
                dataType: 'json',
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                },
                success: function (json) {
                    question = json;
                    renderQuestion(json);
                }
            });
        }

        function renderQuestion(q) {
            $('.questionText').html(q.questionText);
            for (var i = 0; i < q.Choices.length; i++) {
                $('.alternatives').append('<input id="alt' + q.Choices[i].Id + '" name="alternatives" type= radio"' + ' />' + q.Choices[i].Id + '. ' + q.Choices[i].Text + '<br />');
            }
        }
    })
</script>

<div>
    <h4>QuestionDefViewModel</h4>
    <hr />
    <div class="questionText"></div>
    <div class="alternatives"></div>
</div>




</body>
</html>

我正在显示如下所示的输出而不进行渲染,如jquery函数中所述。

{"questionId":0,"questionText":"This is the first question","Choices":[{"choiceId":6000,"questionId":0,"choiceText":"Option A","isCorrect":"Yes       ","Exams":[],"Question":null},{"choiceId":6001,"questionId":0,"choiceText":"Option B","isCorrect":"No        ","Exams":[],"Question":null},{"choiceId":6002,"questionId":0,"choiceText":"Option C","isCorrect":"No        ","Exams":[],"Question":null},{"choiceId":6003,"questionId":0,"choiceText":"Option D","isCorrect":"No        ","Exams":[],"Question":null}]}

1 个答案:

答案 0 :(得分:0)

根据Action Method的动词,Ajax请求类型应为 GET ,而不是 POST

此外,q.Choices [i]应该是 choiceId choiceText ,因为那些是选择实体的财产名称。

对于调试,让我们先从服务器返回静态数据,然后再从数据库中查询。否则,您将不知道错误的位置。

enter image description here

视图

<script type="text/javascript">
    $(function() {
        debugger;
        alert("hi");

        function question() {
            $.ajax({
                url: '/Home/Question',
                type: 'GET',
                cache: false,
                dataType: 'json',
                error: function(jqXHR, textStatus, errorThrown) {
                    alert(errorThrown);
                },
                success: function(json) {
                    question = json;
                    renderQuestion(json);
                }
            });
        }

        function renderQuestion(q) {
            $('.questionText').html(q.questionText);
            for (var i = 0; i < q.Choices.length; i++) {
                $('.alternatives').append('<input id="alt' + q.Choices[i].choiceId +
                    '" name="alternatives" type= radio" />' +
                    q.Choices[i].choiceId + '. ' + q.Choices[i].choiceText + '<br />');
            }
        }

        question();
    });
</script>

<div>
    <h4>QuestionDefViewModel</h4>
    <hr />
    <div class="questionText"></div>
    <div class="alternatives"></div>
</div>

控制器

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Title = "Home Page";

        return View();
    }

    [HttpGet]
    [ActionName("Question")]
    public ActionResult GetQuestionPost()
    {
        QuestionDefViewModel quesDef = new QuestionDefViewModel();
        quesDef.questionText = "Sample Question";
        quesDef.Choices = new List<Choice>
        {
            new Choice { choiceId = 1, choiceText = "One", isCorrect = true},
            new Choice { choiceId = 2, choiceText = "Two", isCorrect = false},
            new Choice { choiceId = 3, choiceText = "Three", isCorrect = true},
        };
        return Json(quesDef, JsonRequestBehavior.AllowGet);
    }
}

其他课程

public class Question
{
    public int questionId { get; set; }   
    public string questionText { get; set; }   
}

public class Choice
{
    public int choiceId { get; set; }
    public string choiceText { get; set; }
    public bool isCorrect { get; set; }
    public int questionId { get; set; }
}