使用razor修改列表中的属性

时间:2017-06-26 18:36:11

标签: asp.net-mvc razor

我想在视图中修改Movie。  我们可以通过代码来完成。

@model MvcMovie.Models.Movie

@{
    ViewBag.Title = "Edit";
}

<h2>Edit</h2>

@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.ReleaseDate)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.ReleaseDate)
        @Html.ValidationMessageFor(model => model.ReleaseDate)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Genre)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Genre)
        @Html.ValidationMessageFor(model => model.Genre)
    </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>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

然而,这是一部电影。但我有很多电影说5.电影模型是一个列表。我怎么能循环呢?

1 个答案:

答案 0 :(得分:0)

您的控制器/视图模型&#34;:

public class MovieViewModel
{
    public int ID { get; set; }
    public string Title { get; set; }
}

public class HomeController : Controller
{
    [HttpPost]
    public ActionResult IndexValid3(IList<MovieViewModel> movieViewModel)
    {
        //set breakpoint here and update db here
        return View(movieViewModel);
    }

    public ActionResult IndexValid3()
    {
        IList<MovieViewModel> list = new List<MovieViewModel>();
        var movieViewModel = new MovieViewModel { ID = 1, Title = "title1"};
        var movieViewModel2 = new MovieViewModel { ID = 1, Title = "title2"};
        list.Add(movieViewModel);
        list.Add(movieViewModel2);
        return View(list);
    }

查看:

@model IList<Testy20161006.Controllers.MovieViewModel>
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>IndexValid3</title>
</head>
<body>
    <div>
        @using (Html.BeginForm())
        {
            <table>

                @for (int i = 0; i < Model.Count(); i++)
                {
                    <tr>
                        <td>@Html.TextBoxFor(m => Model[i].ID)</td>
                        <td>@Html.TextBoxFor(m => Model[i].Title)</td>
                    </tr>
                }
            </table>

            <input type="submit" value="submit" />
        }
    </div>
</body>