How to pass parameters to a partial view in ASP.NET MVC?

后端 未结 6 1301
闹比i
闹比i 2020-11-29 00:45

Suppose that I have this partial view:

Your name is @firstName @lastName

which is accessible through a child o

相关标签:
6条回答
  • 2020-11-29 00:56

    Just:

    @Html.Partial("PartialName", Model);
    
    0 讨论(0)
  • 2020-11-29 00:57

    You need to create a view model. Something like this should do...

    public class FullNameViewModel
    {
         public string FirstName { get; set; }
         public string LastName { get; set; }
    
         public FullNameViewModel() { } 
    
         public FullNameViewModel(string firstName, string lastName)
         {
              this.FirstName = firstName;
              this.LastName = lastName;
         }
    
    }
    

    then from your action result pass the model

    return View("FullName", new FullNameViewModel("John", "Doe"));
    

    and you will be able to access @Model.FirstName and @Model.LastName accordingly.

    0 讨论(0)
  • 2020-11-29 01:00

    Here is another way to do it if you want to use ViewData:

    @Html.Partial("~/PathToYourView.cshtml", null, new ViewDataDictionary { { "VariableName", "some value" } })
    

    And to retrieve the passed in values:

    @{
        string valuePassedIn = this.ViewData.ContainsKey("VariableName") ? this.ViewData["VariableName"].ToString() : string.Empty;
    }
    
    0 讨论(0)
  • 2020-11-29 01:04

    Use this overload (RenderPartialExtensions.RenderPartial on MSDN):

    public static void RenderPartial(
        this HtmlHelper htmlHelper,
        string partialViewName,
        Object model
    )
    

    so:

    @{Html.RenderPartial(
        "FullName",
        new { firstName = model.FirstName, lastName = model.LastName});
    }
    
    0 讨论(0)
  • 2020-11-29 01:08

    Following is working for me on dotnet 1.0.1:

    ./ourView.cshtml

    @Html.Partial(
      "_ourPartial.cshtml",
      new ViewDataDictionary(this.Vi‌​ewData) {
        {
          "hi", "hello" 
        } 
      }
    );
    

    ./_ourPartial.cshtml

    <h1>@this.ViewData["hi"]</h1>
    
    0 讨论(0)
  • 2020-11-29 01:13

    make sure you add {} around Html.RenderPartial, as:

    @{Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});}
    

    not

    @Html.RenderPartial("FullName", new { firstName = model.FirstName, lastName = model.LastName});
    
    0 讨论(0)
提交回复
热议问题