简体   繁体   中英

How do I use Razor to render, edit, and post an variable set of parameters in ASP.NET MVC? Array[] or List<string>

Imagine I have a shopping list, where I don't know how many items will be rendered on the screen, but need to support a long and growing list for view and edit.

How do I create such a form so that I can render it in ASP.NET MVC 4, and also edit it?

Assume my model has an array or a list that I would like to have multiple text boxes for editing:

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)

<fieldset>
    <legend>Movie</legend>

    @Html.HiddenFor(model => model.ID)

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

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

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>

An easy way to do this is to create an editortemplate. Say you class is named Product , create a partial view named "Product.cshtml" under the folder Views/Shared/EditorTemplates .

Note: These names are important, as MVC will look in that specific folder for that specific view name by convention.

Now you can do the following in your view:

View

@model IEnumerable<Product>
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)

    <fieldset>
        <legend>Movie</legend>
        @Html.EditorFor(model => model)
     <p>
        <input type="submit" value="Save" />
    </p>
    </fieldset>
}

Although your calling the editor here for a list of products, MVC is smart enough to recognize that it should invoke the editor for each item of the list. Also, if you use an editor-template, it will make sure that the ID's and names will be set correctly so that the model binder can later reconstruct the list when you post the values to your controller.

Partial view

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

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

You action method (the one you post the form to) would then look like this:

public ActionResult PostList(IEnumerable<Product> products)
{
    // Do whatever a dev's gotta do
}

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