c# - 在部分 View 上返回不同的模型

标签 c# html asp.net-mvc partial-views

我在将带有模型列表的 ViewBag 返回到 PartialView 时遇到了一些麻烦,PartialView 是与 ParentView 不同类型的模型,但我希望仅在渲染的部分 View 内渲染结果父 View 。也许看看我的代码,会更好地理解。

这是我的 Controller :

public ActionResult Search()
{
        //ViewBag.Usuarios = db.User.ToList();
        return View();
}

[HttpGet]
public ActionResult Pesquisar(UserFilter userFilter)
{
        List<UserModel> retorno = new List<UserModel>();
        ViewBag.Mensagem = "Não foi encontrado registro com os filtros informados";

        if (userFilter.Name != null)
        {
             retorno = db.User.Where(x => x.Name.Contains(userFilter.Name)).ToList();
            if (retorno != null)
            {
                ViewBag.Usuarios = retorno;
                return PartialView("Search", ViewBag.Usuarios);
            }
            return View("Search", ViewBag.Mensagem);
        }

        if (userFilter.UserID != 0)
        {
            UserModel retorn = new UserModel();
            var id = Convert.ToInt16(userFilter.UserID);
            retorn = db.User.FirstOrDefault(x => x.UserID == id);                
            return View("Details", retorn);
        }
        return View("Search", ViewBag.Mensagem);
}

这是我的家长 View

@model Sistema_ADFP.Filters.UserFilter


<body>
    <div class="container">
        <h2>Buscar Usuário</h2>
        <form role="form" method="GET" action="/User/Pesquisar">
            <div class="col-lg-12">
                <div class="col-lg-3">
                    <div class="form-group">
                        <label>Nome</label>
                        @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                    </div>
                </div>
                <div class="col-lg-3">
                    <div class="form-group">
                        <label>ID</label>
                        @Html.EditorFor(model => model.UserID, new { htmlAttributes = new { @class = "form-control" } })
                    </div>
                </div>
                <div class="col-lg-3">
                    <div class="form-group">
                        <label>CPF</label>
                        @Html.EditorFor(model => model.CPF, new { htmlAttributes = new { @class = "form-control" } })
                    </div>
                </div>
            </div>
            <div class="clearfix"></div>
            <div class="form-group pull-right">
                <label>&ensp;</label>
                <input type="submit" class="btn btn-primary"/>
            </div>
        </form>
    </div>
    <div class="clearfix"></div>

    @{
        if (ViewBag.Mensagem == null)
        {
            <div id="resultadoLista">
                @{
                    Html.RenderPartial("_List");
                }
            </div>
                    }
                    else
                    {
                    <label>Nenhum registro encontrado</label>
                        }
                    }
</body>

这是我的部分 View

<h4>Usuários</h4>
<div class="table-responsive">
    <table class="table">
        <tr class="inverse" align="center">
            <th>Nome</th>
            <th>Sexo</th>
            <th>Estado Civil</th>
            <th>Educação</th>
            <th>Profissão</th>
            <th>Voluntário</th>
            <th>Data Nascimento</th>
            <th>Ações</th>
        </tr>

        @if (ViewBag.Usuarios != null)
        {


            foreach (var item in ViewBag.Usuarios)
            {
                <tr class="active">
                    <td data-th="Nome"><a class="modal-ajax-link" href="#test-popup">@item.Name</a></td>
                    <td data-th="Sexo">@item.Sex</td>
                    <td data-th="EstadoCivil">@item.MaritalStatus</td>
                    <td data-th="Education" align="center">@item.Education.Description</td>
                    <td data-th="Education" align="center">@item.Profession.Name</td>
                    @if (item.Voluntary)
                    {
                        <td data-th="Voluntario" align="center">Ativo</td>
                    }
                    else
                    {
                        <td data-th="Voluntario" align="center">Inativo</td>
                    }
                    <td data-th="DataNasc" align="center">@item.BirthDate</td>

                    @* data-mfp-src="@HttpContext.Current.Request.Url.Host:@HttpContext.Current.Request.Url.Port/User/Details/2" *@

                    <td data-th="Ações" align="center">
                        <a class="btn btn-info modal-ajax-link" href='@Html.ActionLink("Editar", "Edit",
    new { id = @item.UserID })'><i class="icon_pencil"></i></a>
                        <a class="btn btn-danger modal-ajax-link" href="#delete-modal"><i class="icon_trash_alt"></i></a>
                    </td>
                </tr>
            }
        }

    </table>
</div>

我收到的错误是:

The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[Sistema_ADFP.Models.UserModel]', but this dictionary requires a model item of type 'Sistema_ADFP.Filters.UserFilter'.

我了解错误原因,但我无法找到重置流程并使其工作的方法。有人知道或知道我能做什么吗?

最佳答案

解决此问题的解决方案是不使用 ViewBag 并为 View 创建 ViewModel。 ViewModel 是 View 的类,并将具有 View 的所有必需属性。因此,为了举例,您可以有一个名为:

public class WrapperVM
{
 public UserFilter Filter {get; set;}
 public UserModel Model {get; set;}
}

因此,填充这些属性并将 WrapperVM 传递给父 View (更改为 @model WrapperVM),然后您可以将 usermodel 传递给部分 View 。我希望这会有所帮助。

关于c# - 在部分 View 上返回不同的模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35834773/

相关文章:

c# - 绕过循环依赖

C# DropDownList 以字典作为数据源

html - 如何防止 flex box 随内容增长

html - 如何使 svg 图像适合父容器

c# - ASP.NET MVC 传递数据

c# - 如何在派生 Controller 操作上添加不同的操作过滤器?

c# - 使用非键添加关联

c# - 此时无法获取本地或参数 'x'的值

html - Chrome 中 html 字体大小设置为 6.25% 的 rems 的计算值是 Firefox 中的六倍

c# - 是否有使用 POST 而不是 GET 的 MVC Pager?