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?

4
  • You can't mix C# and JS like this, unless you expect the C# to run completely before the JS does. Commented Jun 19, 2020 at 21:41
  • Then is there any way to pass in the name of the partial page to Html.Partial? Commented Jun 19, 2020 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 Commented Jun 19, 2020 at 21:55
  • A couple questions which might help stackoverflow.com/questions/31576047/… stackoverflow.com/questions/8639278/… Commented Jun 19, 2020 at 21:56

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.