0

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?

nonesuch
  • 167
  • 3
  • 16
  • You can't mix C# and JS like this, unless you expect the C# to run completely before the JS does. – evolutionxbox Jun 19 '20 at 21:41
  • Then is there any way to pass in the name of the partial page to Html.Partial? – nonesuch Jun 19 '20 at 21:54
  • Expose an action method and then use ajax to post to it and have it return a partial. Or switch to blazor – pinkfloydx33 Jun 19 '20 at 21:55
  • A couple questions which might help https://stackoverflow.com/questions/31576047/how-to-pass-javascript-variable-to-server-side-asp-net https://stackoverflow.com/questions/8639278/pass-javascript-variable-to-codebehind – evolutionxbox Jun 19 '20 at 21:56

1 Answers1

0

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.

Bemn
  • 1,291
  • 1
  • 7
  • 22
  • Thanks! That looks promising, but I also have a different model to pass into the partial view based on link path as well. How would I do that? – nonesuch Jun 20 '20 at 14:46
  • I am not sure what will be the content of your model so I assume you want to pass a json object first. In this case you can change the GET call into POST call, and passing the json object as the ajax data. On C# side you need to define a binding model and put it as the param of the action – Bemn Jun 20 '20 at 14:57