AJAX 验证想法 - 包含 ValidationSummary 和 ValidationSummary 验证消息

发布于 2024-07-20 03:44:38 字数 1956 浏览 6 评论 0原文

我一直在研究许多 ASP.Net MVC 客户端验证想法,包括 xVal。 目前它不提供 ValidationSummary,因此我选择执行一个 AJAX post,它循环遍历 ModelState 错误,并使用成功的 AJAX post 上的错误消息更新 DIV。

问题是字段旁边的 ValidationMessage * 不会被填充。 我提出了一个尚未测试的替代想法,因为我还不知道让它工作的完整语法,但我想我会看看你们的想法。

我认为可能存在的一个问题是,当您发布到控制器中的编辑/创建操作方法并且想要返回 JSON 对象时,我不确定这是否合法,因为 JSON 仅用于 GET 操作。

如果您认为这是一个好主意并且想要提供帮助,请留下答案和任何代码片段以使其正常工作。 如果您认为这是一个费脑筋的计划并且可以做得更好,请告诉我如何做。

控制器:

if (!ModelState.IsValid)
{
            var err = ModelState.Where(f => f.Value.Errors.Count > 0);    
            if (Request.IsAjaxRequest())
            {
                   return this.Json(err);
            }
            else
            {
                  return View(PostedItem); 
            }
}

视图:

    $(function() {



    $('#createForm').ajaxForm({
        success:fillSummary
    });

    //click events
    $('#btnSave').click( function(){
        $('#createForm').submit();
    });

    function fillSummary(data) 
    {
       //Loop through the modelstate errors returned
        $.each(data)
       {
            //Append Summary DIV with error message
            //Look for span with the ModelState key name and set it to visible
       }           
    }



    <div id="summary">
       <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.")%>
    </div>
    <form action="<%=Url.Action("Create") %>" method="post" id="createForm">

        <fieldset>
            <div>
                 <label for="Title">Title:</label>
                <%= Html.TextBox("Title",Model.Title) %>
                <%= Html.ValidationMessage("Title", "*") %>
                <span id="val_Title" style="display:none">*</span>              
            </div>
   </form>
   <input type="button" value="Save" id="btnSave" />

I have been looking at many ASP.Net MVC client side validation ideas including xVal. This doesn't provide a ValidationSummary at the moment so I chose to do an AJAX post which loops through ModelState errors and update a DIV with the error messages on a successful AJAX post.

The problem with this is your ValidationMessage * next to the fields won't get populated. I have come up with an alternative idea which I haven't yet tested as I don't know the full syntax to get it working yet but thought I'd see what you guys thought.

One issue I think may be an issue is that when you post to your Edit/Create Action method in the controller and you want to return a JSON object, I'm not sure that is legal as JSON is used for GET actions only.

If you think its a good idea and are wanting to help please leave an answer and any code snippets to get this working. If you think its a hair brained scheme and can be done better please let me know how.

Controller:

if (!ModelState.IsValid)
{
            var err = ModelState.Where(f => f.Value.Errors.Count > 0);    
            if (Request.IsAjaxRequest())
            {
                   return this.Json(err);
            }
            else
            {
                  return View(PostedItem); 
            }
}

View:

    $(function() {



    $('#createForm').ajaxForm({
        success:fillSummary
    });

    //click events
    $('#btnSave').click( function(){
        $('#createForm').submit();
    });

    function fillSummary(data) 
    {
       //Loop through the modelstate errors returned
        $.each(data)
       {
            //Append Summary DIV with error message
            //Look for span with the ModelState key name and set it to visible
       }           
    }



    <div id="summary">
       <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.")%>
    </div>
    <form action="<%=Url.Action("Create") %>" method="post" id="createForm">

        <fieldset>
            <div>
                 <label for="Title">Title:</label>
                <%= Html.TextBox("Title",Model.Title) %>
                <%= Html.ValidationMessage("Title", "*") %>
                <span id="val_Title" style="display:none">*</span>              
            </div>
   </form>
   <input type="button" value="Save" id="btnSave" />

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没有你我更好 2024-07-27 03:44:38

在我当前的 ASP.NET MVC 项目中,我有很多用于 AJAX 的 POST 操作,并且也遇到了验证问题。 我所做的是创建一个包装对象,该对象从每个操作返回,看起来像这样...

public class JsonWrapper
{
   public object Data { get; set; }
   public bool IsError { get; set; }
   public string Message { get; set; }
}

如果操作中的验证没有任何类型的错误,我会将想要返回的任何数据放入数据中财产。 但是,如果存在任何类型的验证错误或其他异常,我会将 IsError 标志设置为 true 并在 Message 属性中设置错误消息。 然后在操作结束时,我将对象序列化为 JSON 并返回它,(是的,您可以通过 POST 操作执行此操作)...

return Json(myJsonWrapper);

从客户端,在我的 AJAX POST 代码的 onSuccess 中,我检查错误,并像这样采取任何必要的操作...(注意,在代码中,从服务器返回的对象已经被 jQuery 反序列化为 JS 对象)

function onSuccess(jsonWrapper) {
    if (!jsonWrapper.IsError) {
        var myDataFromAction = jsonWrapper.Data;
        //Do stuff with my data
    }
    else {
        MessageBox.ShowMessage(jsonWrapper.Message);
    }
}

这不适合您的场景盒子,但你可以做一些类似的概念。 希望这至少能给你一些想法。

In my current ASP.NET MVC project I have a lot of POST actions that I use for AJAX and ran across the validation issue too. What I did was create a wrapper object that gets returned from each of these actions which looks something like this...

public class JsonWrapper
{
   public object Data { get; set; }
   public bool IsError { get; set; }
   public string Message { get; set; }
}

If the validation in the action doesn't have any kind of errors, I place whatever data I want to return in the Data property. However, if there's any kind of validation error or other exception, I set the IsError flag to true and set an error message in the Message property. Then at the end of the action, I serialize the object to JSON and return it, (yes you can do this from a POST action)...

return Json(myJsonWrapper);

From the client side, in the onSuccess of my AJAX POST code, I check for errors, and take any actions neccessary like this... (Note, at this point in the code, the object that got returned from the server has already been deserialized into a JS object by jQuery)

function onSuccess(jsonWrapper) {
    if (!jsonWrapper.IsError) {
        var myDataFromAction = jsonWrapper.Data;
        //Do stuff with my data
    }
    else {
        MessageBox.ShowMessage(jsonWrapper.Message);
    }
}

This won't fit your scenario out of the box, but you could do something similar as a concept. Hope this at least gives you some ideas.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文