简体   繁体   English

如何在MVC中的无序HTML列表中加载锚标记的局部视图?

[英]How to load partial view from anchor tag in unordered HTML list in MVC?

I have a master view that displays an unordered list. 我有一个显示无序列表的主视图。 Inside each element of the list, I have placed an anchor tag in hopes to load a partial view on the same page just in a different spot. 在列表的每个元素内部,我放置了一个锚标记,希望在同一页面上加载一个局部视图,只是在不同的位置。 My goal is to have the page load, and when the user clicks on one element, I would like the partial view to load. 我的目标是加载页面,当用户点击一个元素时,我希望加载部分视图。

Master View: index 主视图:索引

 <ul> <li> <a> apples </a> </li> <li> <a> oranges </a> </li> </ul> 

Partial View: _partialView 部分视图:_partialView

 <div id="rightside"> <h1>Hello</h1> </div> 

Controller for partial view: treeviewController 部分视图控制器:treeviewController

  public PartialViewResult partial()
    {
        return PartialView("_partialView");
    }

I would like 'apples' and 'oranges' to be the hyperlinks to load my partial view. 我希望'apples'和'oranges'成为加载我的局部视图的超链接。 Further down the line, I will be having each item of the list loading different partial views based on what the user selected. 接下来,我将根据用户选择的内容,使列表中的每个项目加载不同的部分视图。

Can anyone suggest the best way to do this in my cshtml file for my master view? 任何人都可以在我的主视图的cshtml文件中建议最好的方法吗?

If you want to render your partial view on some event like button click or a hyperlink click, you will have to use ajax call in jQuery. 如果要在按钮单击或超链接单击等某个事件上呈现局部视图,则必须在jQuery中使用ajax调用。 Create an action method which returns partial view. 创建一个返回部分视图的操作方法。 On button click call this action method and in success of ajax just select the div where you want to load your partial view, add add the response as inner html. 在按钮上单击调用此操作方法,并且在ajax成功时只需选择要加载局部视图的div,添加将响应添加为内部html。

$('#btn').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button(if button type is submit)
var element = $("#YourDiv");  // <--------------Your div where you want to render the partial view. use # if id and . if class
$.ajax({
    url: "/Home/YourAction",    
    success: function (data) {
        if (data.status == "Success") {
           $(element).html(data); //<------------ place the response in your div
        } else {
            alert("Error occurs!");
        }
    },
    error: function () {
        alert("An error has occured!!!");
    }
});

Hope this helps. 希望这可以帮助。

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

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