Search code examples
javascriptc#asp.netpartial-views

Build my Html.Partial string in javascript


I have a javascript function that accepts arguments including the page name to load. I want to be able to build out the call to Html.Partial based on this information. What I'm trying to do is this:

function tabs_itemClick(e) {
   alert("my path should be [" + e.itemData.Path + "]";
   var url = '_' + e.itemData.Path;
   @{Html.Partial(url, new ActivityLog());
}

Obviously this fails because the variable url does not exist for the @{Html.Partial}. How do you get around this?


Solution

  • Looks like what you really want is to render a HTML code segment base on a javascript variable.

    What you need to do is setting up another action in your controller to accept ajax calls from the frontend.

    Define a action accepting the name of partial view in the controller:

    [HttpGet("/api/employee-login")]
    public ActionResult EmployeeLogin(string partialViewName)  
    {
        return PartialView(partialViewName , new ActivityLog());
    }  
    

    After that, create a partial view and place it under the corresponding directory.

    In your frontend, you should fire a GET ajax call with your partial view name e.g.

    var myViewName = "_" + e.itemData.Path;
    $.get("/api/employee-login", { partialViewName: myViewName,} )
      .done(function( data ) {
        /* inject the HTML segment returned into your document */
      });
    /* you may also need some code to handle some situations e.g. view not found */
    

    For example, if e.itemData.Path = "_myView", then you need to have a partial view named _myView.cshtml defined in your project.