简体   繁体   English

将json结果发送到mvc视图

[英]sending json result to the mvc view

I'm sending user request from mvc view to the controller and controller after some processing send result as json object back to the view. 我将一些处理后的用户请求从mvc视图发送到控制器和控制器,将结果作为json对象发送回视图。 my current solution working but I want to render html elements on the view side, not in the js function (as it is now). 我当前的解决方案工作,但我想在视图端渲染html元素,而不是在js函数(现在是)。

function GetTabData(xdata) {
    $.ajax({
        url: ('/Home/GetData'),
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ id: xdata }),

        success: function (result) {
            var data = null;
            data = '<div class="list-products clearfix">
            data += '<a href="/Home/MyData/' + item.Id + '">
....
}

so I want to remove all this divs and other html elements and send pure data and format this on the view, how can I do this? 所以我想删除所有这些div和其他html元素并发送纯数据并在视图上格式化,我该怎么做?

Well, then have your controller action return a PartialView containing the ready-to-be-used HTML fragment instead of a JsonResult: 好吧,那么有你的控制器动作返回一个PartialView包含现成的可以使用的 HTML片段,而不是一个JsonResult:

public ActionResult GetData()
{
    MyViewModel model = ...
    return PartialView(model);
}

Now all you need to do inside your success callback is use the jQuery's .html() function: 现在你需要在成功回调中做的就是使用jQuery的.html()函数:

success: function (data) {
    $('#someContainingDiv').html(data);
}

you would then have a corresponding partial view ( ~/Views/Home/GetData.cshtml ) that will be strongly typed to the view model and render the corresponding HTML: 然后你会有一个相应的局部视图( ~/Views/Home/GetData.cshtml ),它将被强类型~/Views/Home/GetData.cshtml视图模型并呈现相应的HTML:

@model MyViewModel
<div class="list-products clearfix">
@Html.ActionLink("click me", "MyData", "Home", new { id = Mode.Id }, null)
...

As you can see this allows you to use HTML helpers that would generate proper markup and urls, whereas in your original example you were hardcoding urls in your anchor tag like /Home/MyData which is really a very bad thing to do. 正如您所看到的,这允许您使用可以生成正确标记和URL的HTML帮助程序,而在您的原始示例中,您在锚标记中硬编码网址,如/Home/MyData ,这真的是一件非常糟糕的事情。

You should really find the balance between pure JSON data being sent from your contorller actions invoked by an AJAX requests and sending partial views containing markup. 您应该真正找到从AJAX请求调用的控制器操作发送的纯JSON数据与发送包含标记的部分视图之间的平衡。 If you find yourself using lots of string concatenations in your AJAX success callbacks in order to build some HTML markup, then you should probably switch your server side logic to directly return the desired HTML. 如果您发现自己在AJAX成功回调中使用了大量字符串连接以构建一些HTML标记,那么您应该切换服务器端逻辑以直接返回所需的HTML。

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

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