简体   繁体   中英

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

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

Controller for partial view: treeviewController

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

I would like 'apples' and 'oranges' to be the hyperlinks to load my partial view. 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?

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. 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.

$('#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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