【问题标题】:MVC Edit and Send Model View with Partial ViewsMVC 编辑和发送带有局部视图的模型视图
【发布时间】:2021-01-21 16:44:06
【问题描述】:

我正在一个带有复杂模型视图的项目中工作(为简单起见,我举了这个例子):

public class Person
{
    public string Name { get; set; }
    public string LastName { get; set; }
    public string Data3 { get; set; }
    public string Data4 { get; set; }
    public List<Movie> Movies { get; set; }
}

public class Movie
{
    public string Name { get; set; }
    public double Cost { get; set; }
    public double Quantity { get; set; }
}

我有一个主视图人,有两个部分视图“_Movies”和“_Books”

@Html.Partial("_Movies", Model.Movies)

和

@Html.Partial("_Books", Model.Books)

每个部分视图都有一个“添加按钮”,它会打开一个弹出窗口,请求以下数据:

  • 电影名称
  • 成本
  • 数量

这个想法是,当我插入此数据时,它将显示一个带有电影列表和输入数据的网格。能够编辑或删除这些数据。

当我按下底部的“全部保存”按钮时,它会将所有模型数据发布到控制器。

但我不知道如何将模型数据一起发送。我很绝望。

如何编辑和刷新部分视图的数据并获取它们的数据以将完整的模型发送到控制器?

还有我的代码...

主控制器:

public class PersonController : Controller
{
    // GET: Person
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Create()
    {
        ViewBag.Movies = new SelectList(new List<SelectListItem> {
            new SelectListItem { Text = "Lord of the rings", Value = "Lord of the rings"},
            new SelectListItem { Text = "Inception", Value = "Inception"}
        }, "Value", "Text");

        return View(new Person());
    }

    [HttpPost]
    public ActionResult Create(Person person)
    {
        try
        {
            // TODO: Add insert logic here

            return RedirectToAction("Index");
        }
        catch
        {
            return View();
        }
    }

    [ChildActionOnly]
    public ActionResult RefreshMovies(List<Movie> movies)
    {
        ViewBag.Movies = new SelectList(new List<SelectListItem> {
            new SelectListItem { Text = "Lord of the rings", Value = "Lord of the rings"},
            new SelectListItem { Text = "Inception", Value = "Inception"}
        }, "Value", "Text");

        return PartialView("~/Views/Person/_Movies.cshtml", movies ?? new List<Movie>());
    }
}

主视图:

@model MisPruebasMVC.Models.Person

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>General Data</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            <div class="col-md-4">
                @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label" })
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>

            <div class="col-md-4">
                @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label" })
                @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
            </div>
        </div>


        <div class="form-group">
            <div class="col-md-4">
                @Html.LabelFor(model => model.Data3, htmlAttributes: new { @class = "control-label" })
                @Html.EditorFor(model => model.Data3, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Data3, "", new { @class = "text-danger" })
            </div>

            <div class="col-md-4">
                @Html.LabelFor(model => model.Data4, htmlAttributes: new { @class = "control-label" })
                @Html.EditorFor(model => model.Data4, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Data4, "", new { @class = "text-danger" })
            </div>
        </div>


        @Html.Partial("_Movies", Model.Movies ?? new List<MisPruebasMVC.Models.Movie>())

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

部分视图_Movies.cshtml:

@model IEnumerable<MisPruebasMVC.Models.Movie>


<h2>Movies</h2>

<div class="form-group">
    <button id="addISPCost" type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
        Add movie
    </button>
</div>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title" id="exampleModalLabel">New Movie</h3>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                </button>
            </div>

            <div class="modal-body">
                @{
                    var newMovie = new MisPruebasMVC.Models.Movie();
                }

                <div class="form-group">
                    @Html.LabelFor(m => newMovie.Name, "ISP *:", htmlAttributes: new { @class = "control-label col-md-3" })
                    <div class="col-md-9">
                        @Html.DropDownList("Id_ISP", new SelectList(ViewBag.Movies, "Value", "Text"), "Select a movie", new { @class = "form-control", @id = "IdISP" })
                        @Html.ValidationMessageFor(m => newMovie.Name, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(m => newMovie.Cost, "Cost:", htmlAttributes: new { @class = "control-label col-md-3" })
                    <div class="col-md-9">
                        @Html.EditorFor(m => newMovie.Cost, new { htmlAttributes = new { @class = "form-control", @id = "Cost" } })
                        @Html.ValidationMessageFor(m => newMovie.Cost, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(m => newMovie.Quantity, "Quantity:", htmlAttributes: new { @class = "control-label col-md-3" })
                    <div class="col-md-9">
                        @Html.EditorFor(m => newMovie.Quantity, new { htmlAttributes = new { @class = "form-control", @id = "MaximoDiario" } })
                        @Html.ValidationMessageFor(m => newMovie.Quantity, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Cerrar</button>
                <button type="button" class="btn btn-primary" id="saveConfiguracionISP">Aceptar</button>
            </div>
        </div>
    </div>
</div>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Cost)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Quantity)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Cost)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Quantity)
            </td>
        </tr>
    }

</table>

_Books 部分视图与 _Movies 部分视图相同。

我试图将部分放在与主目录相同的目录中并通过调用它们

@Html.Partial("_Movies", Model.Movies ?? new List<MisPruebasMVC.Models.Movie>())

我也试过

@Html.Action("RefreshMovies", Model.Movies)

调用此操作

[ChildActionOnly]
public ActionResult RefreshMovies(List<Movie> movies)
{
    ViewBag.Movies = new SelectList(new List<SelectListItem> {
        new SelectListItem { Text = "Lord of the rings", Value = "Lord of the rings"},
        new SelectListItem { Text = "Inception", Value = "Inception"}
    }, "Value", "Text");

    return PartialView("~/Views/Person/_Movies.cshtml", movies ?? new List<Movie>());
}

即使我尝试将它们移动到共享文件夹内的 EditorTemplates 文件夹中,通过以下方式调用它们:

@Html.EditorFor(m=> m.Movies, "_Movies") @Html.EditorFor(m=> m.Books, "_Books")

但我不知道如何将部分视图中的电影和书籍列表添加到父视图模型中,以通过 BeginForm 中的提交将它们发送到控制器。

有什么想法吗?

【问题讨论】:

  • 请看本教程Code First Approach in Entity Framework祝你好运。
  • 我看到了,但是太简单了。我知道在 MVC 中创建简单的视图、创建、编辑和列出数据。但如果我有一个带有部分视图的视图,其中包含父视图的复杂模型的一部分...
  • 我不确定这里有人会给你你正在等待的完整代码,我建议你开始一些东西(也是简单模型)然后显示你的代码并询问如何添加复杂模型,我相信你会得到更多的答案,祝你好运;)

标签: c# asp.net-mvc razor


【解决方案1】:

我已经实现了将Movies和Books属性中部分视图的数据发送到控制器。

据我所见,视图仅在从控制器接收数据时才获取模型,然后将其解释为HTML并且仅将表单数据发送到控制器,我已解决如下:

在Person 实体中,我添加了字符串类型的属性MoviesRequest 和BooksRequest。在这里,我将收到两个 JSON 格式的数组,我将分别解析为 Movies 和 Books 属性,留下 Person 类,如下所示:

public class Person
{
    public string Name { get; set; }
    public string LastName { get; set; }
    public string Data3 { get; set; }
    public string Data4 { get; set; }
    public List<Movie> Movies { get; set; }
    public List<Book> Books { get; set; }
    public string MoviesRequest { get; set; }
    public string BooksRequest { get; set; }
}

另一方面,在父视图中,我添加了两个隐藏字段来引用这两个新属性:

@Html.HiddenFor(m=> m.MoviesRequest, new { id = "hiddenMovies" })
@Html.HiddenFor(m=> m.BooksRequest, new { id = "hiddenBooks" })

在部分视图_Books 中,我在javascript 中有一个全局变量books,在document.ready 中我设置如下:

books = @Html.Raw(Json.Encode(Model));

而且每次我修改书籍数组时,我都会更新隐藏字段,并分配它:

$("#hiddenBooks").val(JSON.stringify(books));

同窗体局部视图_Movies。

然后,在表单发布中,在控制器中,我所做的就是以这种方式将它们解析为它们的原始属性:

[HttpPost]
public ActionResult Create(Person person)
{
    try
    {
        person.Books = JsonConvert.DeserializeObject<List<Books>>(person.BooksRequest);
        person.Movies = JsonConvert.DeserializeObject<List<Movies>>(person.MoviesRequest);
        
        // TODO: Add insert logic here

        return RedirectToAction("Index");
    }
    catch
    {
        return View();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-06
    • 1970-01-01
    • 2020-06-29
    相关资源
    最近更新 更多