简体   繁体   中英

Change Url.Content according to user click in HTML MVC

I have this piece of HTML page which creates a gallery and shows it. Now the thing is, that i want to change the directory to take the photos from according to the user click. So, at first im creating a navbar where each folder is a button. Then, i have to catch the users click and place the directory name that he choose (@dir.name) in the Url.Content and in the Server.MapPath (replace the '???'). Any ideas about how to do that? Thanks in advance.

 <div class="collapse navbar-collapse" id="myNavbar"> <ul class="nav navbar-nav"> @foreach (var dirPath in Directory.GetDirectories(Server.MapPath("~/Images/Customers/A"))) { var dir = new DirectoryInfo(dirPath); <li id="@dir.Name"><a href="#">@dir.Name</a></li> } </ul> </div> </div> </nav> <div class="preload"></div> <div class="gallery"> <div class="container-fluid"> <div class="row"> @foreach (var imgPath in Directory.GetFiles(Server.MapPath("~/Images/Customers/A/???"), "*.jpg")) { var img = new FileInfo(imgPath); <div class="col-md-3 batas"> <a href="@Url.Content(String.Format("~/Images/Customers/A/???/{0}", img.Name))"><img src="@Url.Content(String.Format("~/Images/Customers/A/???/{0}", img.Name))" data-lity class="img-thumbnail" /></a> </div> } </div> </div> </div> 

Full page is here: https://github.com/ohadki/ShmuliksProject/blob/master/ShmuliksProject/Views/Home/CustomerGallery.cshtml

If you want to update the images when user clicks one of the folder name links, you need to execute some C# code which takes the currently clicked link (the directory name) and get the the files under that using the File.IO api's and use the file names to build the image tags.

I will create a seperate action method which does that. This action method will accept the directory name (which user selected) and gets the files under that, get the file names and build path to the images

public ActionResult GetImages(string directory)
{
    var urlPath = Path.Combine(Url.Content("~/Images/Customers/A/"), directory);
    var pathDir = Server.MapPath(urlPath);
    var files = new List<string>();
    if(Directory.Exists(pathDir))
    {

        var fileNames= Directory.GetFiles(pathDir, "*.jpg")
                                .Select(g=>Path.GetFileName(g));
        var fileUrls=fileNames.Select(a => urlPath +"/"+ a);
        files.AddRange(fileUrls);
    }
    return PartialView("_Images", files);
}

You can see that our action method is passing a list of strings to the partial view, so let's create a partial view called _Images.cshtml , which is strongly typed to a list of strings and write some code to loop through this collection and render the image tags

@model List<string>
<div class="container-fluid">
    <div class="row">
        @foreach (var imgPath in Model)
        {
            <div class="col-md-3 batas">
                <a href="@imgPath">
                    <img src="@imgPath" data-lity class="img-thumbnail" />
                </a>
            </div>
        }
        </div>
</div>

With this code in place, you can try to access the action method by going to the url (with a directory name passed in the query string) and see whether it renders the images.

yourSiteBaseUrl/yourControllerName/GetImages?directory=profile

Assuming profile is a directory name under "~/Images/Customers/A/

If this much code works, next step is to handle the click event on the links. We will wire up a click event on the a tags and stop the default behavior (navigation), get the needed information (the directory name) and make an ajax call to our action method which will return the partial view result we want and update the UI

In the below code snippet, i am adding a data-img-url attribute to each of the a tags and it's value will be the relative path to the GetImages action method with the directory name in the query string.

<div class="collapse navbar-collapse" id="myNavbar">
    <ul class="nav navbar-nav">
        @{ var path = Server.MapPath("~/Images/Customers/A"); }
        @foreach (var dirPath in Directory.GetDirectories(path))
        {
            var dir = new DirectoryInfo(dirPath);
            <li>
                 <a href="#" 
                    data-img-url="@Url.Action("GetImages",
                                  new { directory = dir.Name })">@dir.Name</a>
           </li>
        }
    </ul>
</div>
<div id="gallery" class="gallery"></div>

Now our UI markup is ready, let's write some jQuery code to wire up the click event and then make the ajax call. In the below code snippet, I am using the jQuery load method to make the ajax call and update the DOM

<script>
    $(function () {
        $("a[data-img-url]").click(function (e) {
            e.preventDefault();
            var url = $(this).data("img-url");
            $("#gallery").load(url);
        })
    })

</script>

This is the basic idea. You can make improvements to the code snippets to make it more robust (null check, string concatenation etc)

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