1

I am trying to use a javascript variable as a parameter to a partial view call.

I have a function like this:

function myFunction(divElement, name){

    divElement.append(`@Html.Partial("~/Views/Partials/_First.cshtml", name )`)
}

But this throws an error saying that the variable "name" does not exist in the current context.

Any ideas how I can achieve this?

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
Step
  • 123
  • 4
  • 14
  • 3
    This is not possible in the manner you are attempting because `name` is a JS variable accessible on the client side and the `Html.Partial` is a server side invocation. The two cannot directly interact. I'd suggest reading the answers to [this question](https://stackoverflow.com/q/13840429/519413) if you have any confusion on this topic. To solve your problem I would suggest using an AJAX request to send the `name` variable to an endpoint in your C# code which returns the HTML from the Partial, along with the `name` value parsed in to it – Rory McCrossan Aug 03 '22 at 15:46

1 Answers1

0

You can try to use ajax to return a partial view with js variable:

js:

function myFunction(divElement, name){
     $.ajax({
                type: "POST",
                url: "/Partials/First",
                data: { "name": name },
                success: function (data) {
    
                    divElement.append(data);
                    
                }
            });
    
}

Controller:

public class PartialsController : Controller
    {
        public IActionResult First(string name)
        {
            return PartialView("_First",name);
        }
    }
Yiyi You
  • 16,875
  • 1
  • 10
  • 22