简体   繁体   中英

Pass parameter when creating new Model

I have a view that is showing details of my post with comments, it also rendering a partial view that is responsible for comment adding. The problem is that I don't know how to pass parameter with new Comment() with already existing value in it. That is PostID .

model is Post model that is being used for rendering post data like Body/Title etc...
My code: @Html.Partial("_CommentAdd", new Comment())
What I want to do: @Html.Partial("_CommentAdd", new Comment({ PostID = model.ID}))

Full Code

@using project01.Models
@model project01.Models.Post
@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<fieldset>
    <legend>Post</legend>

    <div class="display-label">Title</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Title)
    </div>

    <div class="display-label">Body</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Body)
    </div>

    <div class="display-label">Tags</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Tags)
    </div>

    <div class="display-label">Date</div>
    <div class="display-field">
        @Html.DisplayFor(model => model.Date)
    </div>
</fieldset>

@Html.Partial("_CommentAdd", new Comment())

@foreach (var comment in Model.Comments)
{
    @Html.Partial("_Comment", comment)
}

Picture with arrow that is showing what I want to achieve.
img

Is your syntax just a bit off? Try this (the property intializers go after the constructor, not as "arguments" to the constructor call):

@Html.Partial("_CommentAdd", new Comment() { PostID = model.ID })

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