Search code examples
c#.net-corerazorfetch-apiasp.net-core-3.1

How to get two string variables passed from the base .cshtml page into the .cs page and the partial view?


I have this in my base.cshtml page:

enter image description here

I then have this in the base.cs

enter image description here

The partial view is as such:

enter image description here

How do I get the strings (testing and testing2) into base.cs and then into the partial view?


Solution

  • You can pass a value from JS code to server-side code using query strings. In your case:

    .fetch('testpage/?handler=TestPartial&' + 
      new URLSearchParams({ testing, testing2 }))
    

    This will request the URL testpage/?handler=TestPartial&testing=xxx&testing2=yyy

    You need to declare those parameters in your server-side method to parse and receive them:

    public PartialViewResult OnGetTestPartial(string testing, string testing2)
    {
      ...
    }
    

    Your parameters will be passed to your method this way. To show these parameters in the view, you need to pass it as a model to the view:

    public class TestPartialViewModel
    {
      public string Testing { get; set; }
      public string Testing2 { get; set; }
    }
    
    public partial ViewResult OnGetTestPartial(string testing, string testing2)
    {
      return Partial("Partials/TestPartial", new TestPartialViewModel 
      { 
        testing, 
        testing2
      });
    }
    

    and declare your viewmodel class as the model for your view at the top of your view:

    @model TestPartialViewModel
    
    The value of testing is @Model.Testing
    The value of testing2 is @Model.Testing2