asp.net mvc 使用Java Script 渲染一个局部视图

18 浏览
0 Comments

asp.net mvc 使用Java Script 渲染一个局部视图

我想创建一个部分视图,以表格形式显示数据。\n我将使用一个选择元素来选择服务。\n当用户在下拉框中选择了一个服务时,我想调用一个带有服务ID号的部分视图:\n我该如何做到这一点?\n这是一个将呈现部分视图的动作方法:\n

//
// GET: /Service/ServiceStatusLogs/1
public ActionResult ServiceStatusLogs(int id)
{
   var db = new EFServiceStatusHistoryRepository();
   IList logs = db.GetAllStatusLogs(id);
   return View("_ServiceStatusLogs", logs);
}

\n这是返回页面的主要动作方法:\n

//
// GET: /Services/Status
public ActionResult Status()
{
  IList services;
  using (var db = new EFServiceRepository())
  {
    services = db.GetAll();
  }
   return View(services);
}

0
0 Comments

问题的原因是在加载部分视图后,Jquery.datatable无法正常工作。解决方法如下:

1. 确保在加载部分视图之后重新初始化Jquery.datatable。可以在加载部分视图的成功回调函数中添加以下代码:

$('#user_table').DataTable();

这将重新初始化Jquery.datatable并使其在加载的表格上生效。

2. 如果仍然无法正常工作,可能是因为部分视图中的表格元素与Jquery.datatable的要求不符。可以尝试在部分视图中添加以下代码,以确保表格元素具有正确的HTML结构:

通过以上两个步骤,您应该能够解决加载部分视图后Jquery.datatable无法正常工作的问题。

0
0 Comments

问题的出现原因是:在ASP.NET MVC中,如果想要使用JavaScript动态加载并渲染Partial View,需要使用ajax功能来实现。上述代码中,通过在ComboBox的change事件中使用ajax来获取服务的Id,并将Id作为参数传递给Controller的Action。在Action中,使用EFServiceStatusHistoryRepository从数据库中获取相关数据,并将数据传递给Partial View,最后将Partial View作为结果返回。

解决方法是:使用$.ajax方法发送GET请求到指定的Action,将serviceId作为参数传递。在成功的回调函数中,将返回的结果填充到指定的Div容器中,实现Partial View的渲染。需要注意的是,在Controller的Action中需要返回Partial View而不是View。

以下是完整的代码示例:

// Combo box change event
$("#comboboxName").change(function () {        
    // Get service Id 
    var serviceId = $("#comboboxName").val();
    
    // Do ajax call  
    $.ajax({
        type: 'GET',
        url: "/Service/ServiceStatusLogs/",
        data: {                          
            Id: serviceId  // Data need to pass as parameter                       
        },           
        dataType: 'html', // dataType - html
        success: function(result) {
            // Create a Div around the Partial View and fill the result
            $('#partialViewContainerDiv').html(result);                 
        }
    });           
});
// GET: /Service/ServiceStatusLogs/1
public ActionResult ServiceStatusLogs(int id)
{
    var db = new EFServiceStatusHistoryRepository();
    IList logs = db.GetAllStatusLogs(id);
    return PartialView("_ServiceStatusLogs", logs);
}

通过以上代码,我们可以在ComboBox的change事件中使用ajax来动态加载并渲染Partial View。在Controller的Action中,我们从数据库中获取相关数据,并将数据传递给Partial View,最后将Partial View作为结果返回。这样就实现了通过JavaScript动态加载并渲染Partial View的功能。

0