【问题标题】:Display same modal form for different db entities为不同的数据库实体显示相同的模式形式
【发布时间】:2018-10-10 15:36:30
【问题描述】:

我有几个实体实现了IEntity 接口(在现实世界中我有 10 个实体)。

public interface IEntity
{
    short Id { get; set; }
    string Name { get; set; }
}
public partial class Part: IEntity { }
public partial class Localization : IEntity { }

我正在显示每个实体的列表(在表格中),并且我想显示一个模式表单来编辑实体的名称,而无需重复代码。

所以我有一个显示列表的部分视图和一个启动模态表单的按钮:

@model IEnumerable<IEntity>


@foreach (IEntity item in Model)
{
    <tr>
        <td>
            @Html.DisplayFor(m => item.Name)
        </td>
        <td>
            <button  data-id="@item.Id" onclick="editEntity(this)">
                <i class="fa fa-edit text-primary"></i>
            </button>
        </td>
    </tr>
}
//Here the modal container part
<div class="modal fade" id="editModal" aria-hidden="true">
    <div id="editModalContainer">
    </div>
</div>

现在,模态形式也是局部视图(这里简化了):

@using (Html.BeginForm())
{
    @Html.ValidationMessageFor(m => m.Name, "", new { @class = "text-danger" })
    @Html.TextBoxFor(m => m.Name)
    <button type="submit" id="submitEdit" class="btn btn-primary">Enregistrer</button>  
}

此时我正在以这种方式通过 ajax 渲染模式:

function editEntity(clickedEntity) {
//I need the type of entity to get right modal title and so on
var type = $(clickedEntity).closest("div").attr('data-entityType');
var entityId = $(clickedEntity).attr('data-id');

$.ajax({
    type: "GET",
    url: "/Defaults/GetEntityModal",
    data: { id: entityId, entityType: type },
    success: function (response) {  
        $("#editModalContainer").html(response);
        $("#editModal").modal('show');
    },
    failure: function (response) {
        alert("failure");
    },
    error: function (response) {
        alert("error");
    }
});

控制器的方法是:

[HttpGet]
public ActionResult GetEntityModal(EditEntityModalView entityModel)
{
    IEntity entity = _entitiesService.GetEntity(entityModel.EntityType, entityModel.Id);
    entityModel.Name = entity.Name;
    return PartialView("_ModifyEntityModal", entityModel);
}

但是在模态模型的服务器端验证的下一步中我遇到了很多麻烦。

所以我的问题是,在这种情况下,它是呈现模式的正确方法还是我必须为表格中的每个条目制作一个表单?

【问题讨论】:

    标签: jquery ajax razor model-view-controller


    【解决方案1】:

    这是正确的方法,但是模态视图必须先渲染,然后才能被 ajax 更新:

    <div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div id="editModalContainer">
            @{Html.RenderPartial("_ModifyEntityModal", Model.EditEntityModalView);}
        </div>
    </div>
    

    【讨论】:

      猜你喜欢
      • 2019-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-30
      • 1970-01-01
      • 2021-10-08
      • 2012-04-11
      相关资源
      最近更新 更多