简体   繁体   中英

Pass value to a partial view

Im trying to pass a paramater to a partial view. The view will create a new post object, id like to pass it a paramater to be used. Is this possible? I have seen view data dictionary passed around while tring to figure it out buy im not sure how to use it.

Partial View Call

@Html.Partial("_AddPost", new S.Models.Post())

_addpost

@model S.Models.Post

<h2>Create</h2>

    `
@using (Ajax.BeginForm("CreatePost", "Wall", new AjaxOptions
{
    HttpMethod = "post",
    InsertionMode = System.Web.Mvc.Ajax.InsertionMode.InsertAfter,
    UpdateTargetId = "newStatus"}))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true) 

    <fieldset>
        <legend>Post</legend>

        <div class="editor-label">

        </div>
        <div class="editor-field">

 @Html.HiddenFor(model => model.wallName, new { Value = //data i want passed from main view })
 @Html.HiddenFor(model => model.Username, new { Value = User.Identity.Name })

        </div>


        <div class="editor-label">
            @Html.LabelFor(model => model.PostContent)
        </div>
        <div class="editor-field">
            @Html.EditorFor(model => model.PostContent)
            @Html.ValidationMessageFor(model => model.PostContent)
        </div>

        @{
    TempData["returnURL"] = Request.Url.AbsoluteUri;
        }
        <p>
            <input type="submit" id="postStatus" value="Create" />
        </p>
    </fieldset>
}

Since the value is from your main view model and you are calling your partial from the main view, just set the value of your model object in your constructor when you call the new S.Models.Post.

@Html.Partial("_AddPost", new S.Models.Post({wallPost = model.Value}))

If you have items in your ViewData or ViewBag from the main view, you can also pass those into the partial by adding a third parameter

@Html.Partial("_AddPost", new S.Models.Post(), ViewData)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM