c# - 在 ASP.NET MVC 中,当 Model.isvalid 为 false 时如何将验证消息重定向并显示回局部 View

标签 c# asp.net-mvc validation asp.net-mvc-4

当针对模型类验证模型时,我试图将验证消息显示回部分 View 。但是当失败时,我不知道如何将验证错误消息从 POST 的位置显示回 VIEW被解雇 这是部分 View 的代码 (_CreateCustomer)

 @model Banking.Models.Customer
 @Html.ValidationSummary(true)

<fieldset>
    @using (Html.BeginForm("CreateCustomer", "Customer",FormMethod.Post))
        {
            @Html.ValidationSummary(true)

    <div id="cusCreate">
        <table id="createCustomer">
            <tr><td>Please enter ther details of the Customer </td></tr>
            <tr>
                <td>First Name : </td>
                <td>
                    @Html.TextBoxFor(model => model.FirstName)
                    @Html.ValidationMessageFor(model => model.FirstName)
                </td>
                <td>Last Name : </td>
                <td>
                    @Html.TextBoxFor(model => model.LastName)
                    @Html.ValidationMessageFor(model => model.LastName)
                </td>
            </tr>
            <tr>
                <td>Address : </td>
                <td>
                    @Html.TextAreaFor(model => model.Address)
                    @Html.ValidationMessageFor(model => model.Address)
                </td>
                <td>City : </td>
                <td>
                    @Html.TextBoxFor(model => model.City)
                    @Html.ValidationMessageFor(model => model.City)
                </td>
            </tr>
            <tr>
                <td>State : </td>
                <td>
                    @Html.TextBoxFor(model => model.State)
                    @Html.ValidationMessageFor(model => model.State)
                </td>
                <td>Pincode :</td>
                <td>
                    @Html.EditorFor(model => model.Pincode)
                    @Html.ValidationMessageFor(model => model.Pincode)
                </td>
            </tr>
            <tr>
                <td>Phone : </td>
                <td>
                    @Html.EditorFor(model => model.Phone)
                    @Html.ValidationMessageFor(model => model.Phone)
                </td>
                <td>Email :</td>
                <td>
                    @Html.TextBoxFor(model => model.Email)
                    @Html.ValidationMessageFor(model => model.Email)
                </td>
            </tr>
            <tr>
                <td style="align-content:center" colspan="4"> </td>
            </tr>
        </table>
        <input type="submit" value="CreateCustomer" id="cusSubBtn" />
    </div>

    }
</fieldset>

以下是加载局部 View 的 View 代码

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

@Scripts.Render("~/bundles/jquery")
<html>
<head>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#CusCreatebtn').click(function (event) {
                $("#CusDynamicPortion").hide();
                $("#CusDynamicPortion").load("/Customer/CreateCustomerData");
                $("#CusDynamicPortion").show();
            });
        });
    </script>
</head>
<body >
    <div id="CusDynamicPortion">
        <table id="customeroptions" style="width:100%">
            <tr>
                <td><input type="button" id="CusCreatebtn" value="Add New Customer" /> </td>
                <td><input type="button" id="CusViewbtn" value="View Customer" /> </td>
            </tr>
        </table>

    </div>
</body>
</html>

对应 Controller 类(Customer.cs)的代码

public ActionResult CreateCustomerData()
{
    return PartialView("_CreateCustomer");
}

[HttpPost]
public ActionResult CreateCustomer(Models.Customer model)
{
    if (ModelState.IsValid)
    {
        string firstName = model.FirstName;
        int pinCode = model.Pincode;
        return Content("Customer first name is " + firstName);
    }
    else
    {
        return RedirectToAction("index");
    }
}

最佳答案

当您保存表单时,您的网站会发出如下所示的 POST 请求:

POST http://localhost:62186/Customer/CreateCustomer HTTP/1.1
FirstName=&LastName=&Address=&City=&State=&Pincode=&Phone=&Email=

当您的代码知道 Model.IsValid 为 false 时,它​​会使用 RedirectToAction 方法发送 302 HTTP 响应并重定向到/Customer 地址。然后浏览器像这样执行 GET 请求:

GET http://localhost:62186/Customer HTTP/1.1

如您所见,您的请求数据已完全丢失。您需要做的第一件事是将 RedirectToAction 替换为 View 方法并指向您的父 View 。它将在 POST 请求的上下文中加载您的 View 。这是您的 POST 操作的样子:

[HttpPost]
public ActionResult CreateCustomer(Models.Customer model)
{
    if (ModelState.IsValid)
    {
        string firstName = model.FirstName;
        int pinCode = model.Pincode;
        return Content("Customer first name is " + firstName);
    }
    else
    {
        return View("Index");
    }
}

当您的 View 在 POST 请求后呈现并且您单击“添加新客户”时,将执行另一个 GET 请求并且参数丢失:

GET http://localhost:62186/Customer/CreateCustomerData HTTP/1.1

避免此错误的最佳方法是在父 View 中预呈现局部 View 。您可以使用 Html.Partial 方法将局部 View 加载到另一个 View 中。然后你可以用 div 元素围绕这个声明并使用 JavaScript 来隐藏和显示它。您的父 View 应如下所示:

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

@Scripts.Render("~/bundles/jquery")
<html>
<head>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#CusForm").hide();
            $('#CusCreatebtn').click(function (event) {
                $("#CusForm").show();
            });
        });
    </script>
</head>
<body>
    <div id="CusDynamicPortion">

        <div id="CusForm">
            @Html.Partial("_CreateCustomer")
        </div>

        <table id="customeroptions" style="width:100%">
            <tr>
                <td><input type="button" id="CusCreatebtn" value="Add New Customer" /> </td>
                <td><input type="button" id="CusViewbtn" value="View Customer" /> </td>
            </tr>
        </table>
    </div>
</body>
</html>

通过这两个修复,您的代码将正常工作。但是如果你想使用 AJAX 来加载和发送表单,那么你应该阅读一些关于 Ajax.BeginForm 辅助方法的内容。

关于c# - 在 ASP.NET MVC 中,当 Model.isvalid 为 false 时如何将验证消息重定向并显示回局部 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33256403/

相关文章:

asp.net-mvc - Ninject + ASP.NET MVC + InRequestScope

ruby-on-rails - 如何添加仅接受超过特定值的年份的验证,Ruby on Rails

c# - MySQL .NET 连接器 6.9.8

c# - 如何修复 ListView 中的控件重影问题?

c# - 自己的服务 - 没有注册类型的服务

javascript - 如何验证电子邮件地址与网站域名是否匹配?

javascript - 有没有办法进行部分 parsley.js 验证?

c# - 泛型的泛型结构 : can I create overloads for specific kinds(? 中的运算符重载)?

asp.net - 在设计网页时遇到布局问题(1600 X 900 像素)

jquery - MVC 与 jquery 捆绑在调试中不起作用