【问题标题】:What is the better way to reload a part of the view with new data in ASP.Net MVC?在 ASP.Net MVC 中用新数据重新加载视图的一部分的更好方法是什么?
【发布时间】:2020-12-14 10:37:54
【问题描述】:

目前,我的视图中有很多表。我第一次用 HTML 中的 Model 属性值加载它。

但我必须根据下拉框中的更改重新加载表格。为此,我正在进行 ajax 调用并使用新数据替换客户端(Javascript)中的表。

现在,我想知道,还有其他更好的方法来实现此功能吗?就像 Asp.Net 引擎本身负责用新数据加载特定表一样,所以我不想在 JS 中重新创建 html 结构。

在这种情况下,部分视图对我有帮助吗?

【问题讨论】:

标签: c# ajax asp.net-mvc


【解决方案1】:

这不是完整的答案,只是你可以做什么的一个想法:

创建控制器

public class RenderPartialController
{
  [HttpGet]
  public IActionResult RenderPartial(string viewName, string data)
  {
    //do something with data
    //create model for that view
    return View(viewName, model);
  }
}

然后在js中你可以进行ajax调用并用响应中的数据替换html

function updatePartial(viewName, dataObject, selector){
  let data = JSON.stringify(dataObject); 

  $.get(`...RenderPartial?viewName=${viewName}&data=${data}`, res => {
    $(selector).html($(res).find(selector).html());
  });
}

updatePartial('_TableView', {id: 1}, '#mainTable');

请记住,如果您在旧 html 中有任何 JS 绑定,它们将被删除,您需要重新应用它们。

这只是一个想法,不是解决方案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多