简体   繁体   English

MVC:JSON的结果自动填充视图

[英]MVC: Result from JSON Automatically fill View

I am stuck in publishing the result from JSON so left the success portion blank. 我被困在发布JSON的结果,所以成功部分留为空白。

View 视图

@model MvcApplication2.Models.About

@{
    ViewBag.Title = "About";
}


<p> @Html.DisplayFor(m=>m.test) </p>
<p> @Html.DisplayFor(m=>m.test1) </p>

Model 模型

public class About
    {
        public string test { get; set; }
        public string test1 { get; set; }
    }

Controller 控制者

public class HomeController : Controller
    {
       public JsonResult About()
        {
            ViewBag.Message = "Your app description page.";
            About ab = new About()
                              {
                                  test = "a",
                                  test1 = "b"
                              };
            return Json(ab, JsonRequestBehavior.AllowGet);
        }
}

JQuery in external file jQuery在外部文件

$(document).ready(function () {

    var itemName = "#btn-about";

    $(itemName).click(function () {
        $.ajax({
            type: 'GET',
            dataType: 'Json',
            url: '/Home/About',
            success: function (data) {
                var option = '';

            },
            error: function (xhr, ajaxOption, thorwnError) {
                console.log("Error")
            },
            processData: false,
            async: true
        });
    });
});

=> I am a bit confused now. =>我现在有点困惑。 Altough I get a result in JSON format using AJAX, I want to publish it in this View 'About'. 尽管我使用AJAX获得了JSON格式的结果,但我想将其发布在此“关于”视图中。 The View already have @model defined, so as soon as I get the result, I want the view to load it automatically as I don't think its a good option to create html controls in Javascript. 视图已经定义了@model,因此,一旦获得结果,我希望视图自动加载它,因为我认为使用Javascript创建html控件不是一个好的选择。

=> Is it possible or do I have to fill control one by one. =>有可能还是我必须一一填写控件。

=> I am new in to MVC, so could you let me know any good suggestion. =>我是MVC的新手,所以可以让我知道任何好的建议。

Controller: 控制器:

public ActionResult About()
{
    var model = repo.GetModel();
    return PartialViewResult("about", model);
}

jQuery: jQuery的:

$.ajax("/Controller/About/", {
    type: "GET",
    success: function (view) {
        $("#aboutDiv").html(view);
    }
});

In Main View: 在主视图中:

<div id="aboutDiv"><div>

You need to give your elements some id or class that will allow you to interact with them easily on the client. 您需要为您的元素提供一些ID或类,以使您可以轻松地在客户端上与它们进行交互。 Then, when you get your response, take the values from the JSON data and update the elements (using the id/class to find it) with the new value. 然后,当您获得响应时,请从JSON数据中获取值,并使用新值更新元素(使用id / class进行查找)。 I'm assuming you don't have any special template defined for your strings, adjust the selectors in the code as necessary to account for it if you do. 我假设您没有为字符串定义任何特殊的模板,如果需要,请根据需要调整代码中的选择器。

View 视图

<p class="testDisplay"> @Html.DisplayFor(m=>m.test) </p>
<p class="test1Display"> @Html.DisplayFor(m=>m.test1) </p>

Client code 客户代码

$(document).ready(function () {

    var itemName = "#btn-about";

    $(itemName).click(function () {
        $.ajax({
            type: 'GET',
            dataType: 'Json',
            url: '/Home/About',
            success: function (data) {
                $('.testDisplay').html(data.test);
                $('.test1Display').html(data.test1);
            },
            error: function (xhr, ajaxOption, thorwnError) {
                console.log("Error")
            },
            processData: false,
            async: true
        });
    });
});

Instead of returning the data you will have to return the view as string and the use jquery to replace the result. 除了返回数据之外,您还必须将视图作为字符串返回,并使用jquery替换结果。

Controller: 控制器:

    public JsonResult About()
    {
        var model = // Your Model
        return Json((RenderRazorViewToString("ViewNameYouWantToReturn", model)), JsonRequestBehavior.AllowGet);
    }

    [NonAction]
    public string RenderRazorViewToString(string viewName, object model)
    {
        ViewData.Model = model;
        using (var sw = new StringWriter())
        {
            var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
            var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
            viewResult.View.Render(viewContext, sw);
            viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
            return sw.GetStringBuilder().ToString();
        }
    }

Then using jquery you can replace the result in container for eg: div as follows: 然后使用jquery可以将结果替换为例如div的容器,如下所示:

    $.ajax({
        type: 'GET',
        dataType: 'Json',
        url: '/Home/About',
        success: function (result) {
             $("#divId").replaceWith(result);
        },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM