如何正确使用带有 Ajax Begin 窗体的分部视图

本文关键字:窗体 视图 Begin Ajax 何正确 | 更新日期: 2023-09-27 18:31:55

我在我的index.cshtml中有以下代码

@using Kendo.Mvc.UI;
@using xx.Relacionamiento.Modelo.Bussiness.Entities;
@using xx.Relacionamiento.Modelo.Bussiness.Entities.Custom;
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
@model PresupuestosGenerale
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
    }
<div class="">
    <div id="ContenedorPresupuestoGeneral">
        @Html.Partial("CreateOrEditPresupuestoGeneralxx", Model)
    </div>
    <br />
    <br />

然后我有以下部分视图

@using xx.Relacionamiento.Modelo.Bussiness.Entities.Enumeraciones;
@using xx.Relacionamiento.Modelo.Bussiness.Entities;
@using Kendo.Mvc.UI;

@model PresupuestosGenerale
<div class="panel panel-default">
    <div class="panel-heading">
        @using (Ajax.BeginForm("CreateOrEditPresupuestoGeneralxx", new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = "ContenedorPresupuestoGeneral", InsertionMode = InsertionMode.Replace }))
        {
            @Html.HiddenFor(h => h.PresupuestoGeneralId)
            @Html.Hidden("Categoria",CategoriaEvento.xx.ToString())
            <div class="row">
                <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
                    <label>Presupuesto Global xx</label>
                    <br />
                    @(Html.Kendo().NumericTextBoxFor(e => e.PresupuestoGlobal)
                    .Decimals(0)
                    .DecreaseButtonTitle("Decrementar")
                    .IncreaseButtonTitle("Incrementar")
                    .Format("c0")
                    .HtmlAttributes(new { style = "width:99%;" })
                    .Max(1000000000000000000)
                    .Min(1)
                    .Step(100000)
                    .Placeholder("Presupuesto General xx"))
                    @Html.ValidationMessageFor(v => v.Valor, "", new { @style = "color: rgba(247, 20, 10, 0.97);" })
                </div>
                <div class="col-md-3">
                    <br />
                    <input type="submit" class="form-control btn btn-primary" value="Guardar Presupuesto" onclick="SetMostrarVentana();" />
                </div>
            </div>
        }

    </div>
</div>
<script type="text/javascript">
    $(function () {
        MostrarVentanaLoading = false;
        @if (!string.IsNullOrEmpty(ViewBag.MensajeError))
        {
            @:mostrarMensajeAlertGlobal("@ViewBag.MensajeError",15000)
        }
        else if (!string.IsNullOrEmpty(ViewBag.MensajeSuccess))
        {
            @:mostrarMensajeAlertSuccessGlobal("@ViewBag.MensajeSuccess", 15000);
        }
    });
</script>

然后在我的控制器上,我有业务逻辑,根据条件返回不同的内容

 public ActionResult CreateOrEditPresupuestoGeneralxx(PresupuestosGenerale presupuestoGeneralxx)
        {
            try
            {
                ModelState.Remove("PresupuestoGlobal");
                if (presupuestoGeneralxx == null)
                {
                    return PartialView();
                }
                if (!ModelState.IsValid)
                {
                    return PartialView(presupuestoGeneraxx);
                }
                if (presupuestoGeneralxx.Valor < 1)
                {
                    ModelState.AddModelError("Valor", "Por favor ingrese un presupuesto total");
                    return PartialView(presupuestoGeneralxx);
                }

因此,当用户提交表单时,索引视图中的容器将替换为新的 html。

代码

运行良好,但是我觉得代码很丑陋,不可维护且难以阅读。

我的问题是,对于 asp.net mvc 和 ajax,是否有一种更好、更有条理的方法可以用更具可读性的代码来实现同样的事情?

如何正确使用带有 Ajax Begin 窗体的分部视图

我会重构将ajax表单移出部分的视图。这样,在表单中呈现的完整部分在 ajax 帖子上刷新,保持对容器结构的不了解和解耦,并且每个视图都有自己的责任:

Index.cshtml

<div class="panel panel-default">
    <div class="panel-heading">
        @using (Ajax.BeginForm("CreateOrEditPresupuestoGeneralxx", new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = "form-content", InsertionMode = InsertionMode.Replace }))
        {
            <div id="form-content">
                @Html.Partial("CreateOrEditPresupuestoGeneralxx", Model)
            </div>
        }
    </div>
</div>

CreateOrEditPresupuestoGeneralxx.cshtml

@using xx.Relacionamiento.Modelo.Bussiness.Entities.Enumeraciones;
@using xx.Relacionamiento.Modelo.Bussiness.Entities;
@using Kendo.Mvc.UI;
@model PresupuestosGenerale
@Html.HiddenFor(h => h.PresupuestoGeneralId)
@Html.Hidden("Categoria",CategoriaEvento.xx.ToString())
<div class="row">
...

这是我在一些项目中使用的示例之一。在此示例中,不仅呈现PartialView,还将DropdownList值传递给PartialView并显示在其上。

视图:

<div id="divPartialView">
    @Html.Partial("~/Views/MyPartialView.cshtml", Model)
</div>

$(document).ready(function () { 
    $(".SelectedCustomer").change(function (event) {
        $.ajax({
            url: '@Url.Action("GetPartialDiv", "Home")',
            data: { id: $(this).val() /*add other additional parameters */ },
            cache: false,
            type: "POST",
            dataType: "html",
            success: function (data, textStatus, XMLHttpRequest) {
                SetData(data);
            },
            error: function (data) { onError(data); }
        });
    });
    function SetData(data) {
        $("#divPartialView").html(data); //HTML DOM replace
    } 
});

控制器:

[HttpPost]
public PartialViewResult GetPartialDiv(int id /* ddl's selectedvalue */)
{
    Models.GuestResponse guestResponse = new Models.GuestResponse();
    guestResponse.Name = "this was generated from this ddl id:"; 
    return PartialView("MyPartialView", guestResponse);
}