在ASP.Net MVC中,ModelState可以与ajax更新一起使用吗? [英] In ASP.Net MVC, can ModelState be used with an ajax update?

查看:117
本文介绍了在ASP.Net MVC中,ModelState可以与ajax更新一起使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是追踪上一个问题,我以前曾经将错误传回客户端,但也属于ModelState。

This is a follow up to a previous question that I had before about passing an error back to the client, but also pertains to the ModelState.

有没有人成功使用Nerd Dinner方法,但是使用Ajax?所以Nerd晚餐的更新如此。

Has anyone successful used the Nerd Dinner approach, but with Ajax? So Nerd Dinner does an update as so.

[AcceptVerbs(HttpVerbs.Post)]
    public ActionResult Edit(int id, FormCollection formValues) 
{
    Dinner dinner = dinnerRepository.GetDinner(id);
    try 
    {
        UpdateModel(dinner);
        dinnerRepository.Save();
        return RedirectToAction("Details", new { id=dinner.DinnerID });
    }
    catch 
    {
        foreach (var issue in dinner.GetRuleViolations()) {
        ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
    }
        return View(dinner);
    }
}

使用jQuery $ .ajax

Using jQuery $.ajax

function hijack(form, callback, errorFunction, format) {
    $.ajax({
        url: form.action,
        type: form.method,
        dataType: format,
        data: $(form).serialize(),
        success: callback,
        error: function(xhr, textStatus, errorThrown) {
            errorFunction(xhr, textStatus, errorThrown);
        }
    });
}

Ajax,控制器的try部分成为

Ajax, the "try" part of the controller becomes

    try 
{
    UpdateModel(dinner);
    dinnerRepository.Save();
    return PartialView("PartialDetails", new { id=dinner.DinnerID });
}

,但是你对catch部分有什么作用?

, but what do you do about the catch part?

发送错误的一个简单的错误处理方案将是

A simple error handling solution to send back an error would be

catch(Exception ex)
{
    Response.StatusCode = 500;                
    return Content("An Error occured.");
    //throw ex;
}

,但是不通过强大的模型建立在MVC中。我想到了很多选项,但是我真的想要两件事:

, but that doesn't pass through the robust modelstate built into MVC. I thought of a number of options, but I really want 2 things:


  1. 我希望在jQuery的错误属性中处理错误。 / li>
  2. 我想尽可能使用内置的ASP.Net MVC验证逻辑。

这可能吗?如果没有,你知道什么是最好的选择?

Is this possible? If not, what are the best alternatives that you know of?

非常感谢。

更新
我没有将此标记为已回答,因为我还没有实现我认为最有效的方式。

Update I haven't marked this as answered yet, because I haven't yet implemented what I think will work best.

我已经决定我不喜欢成功=>发送刷新列表,失败=>发送我正在采取的错误消息方法。我这样做是为了减少通话次数,但刷新的列表真的被设置在页面上。尝试做这两个操作都将弹出窗口与其整个页面进行紧密绑定。

I have decided that I don't really like the success => send refreshed list, failure => send error message approach that I was taking. I did this to reduce the number of calls, but a refreshed list is really being set to the page. Trying to do both tightly binds the popup to its overall page.

当对话框关闭时,我将添加一个自定义jQuery事件来刷新主页面列表。实质上是观察者模式。我喜欢这样的想法:页面对弹出窗口说完成后告诉我(也称为关闭),而不必告诉弹出窗口为什么。它需要一个额外的电话,但我不认为这是一个大问题。

I am going to add a custom jQuery event refresh the master page list when the dialog closes. In essence, it's the observer pattern. I like the idea that the page says to the popup "tell me when you're done" (aka closed), without having to tell the popup why. It does require an additional call, but I don't see that as a big issue.

我仍然不知道我喜欢/不喜欢服务器端验证,我正在考虑使用客户端验证。虽然服务器端验证看起来像是干净的分层,但它也有一些问题,其中包括:

I'm still not sure how well that I like/dislike server-side validation and I'm considering going with client-side only validation. While server side validation seems like clean layering, it also has a number of problems, including:

1)它将质量检查结束而不是开始。与制造类似的是一辆汽车,当它到达经销商时进行测试,而不是在其正在建造的过程中进行测试。

2)它违反了Ajax的意图。 Ajax不仅仅是发送异步事件,而且还只发送我需要的东西,只收到我需要的东西。为了提供错误的详细信息,返回整个modelstate似乎并没有与Ajax。

1) It puts quality checks at the end, instead of the beginning. An analogy to manufacturing would be a car that's tested when it arrives at the dealer, instead at the points in the process where it's being built.
2) It violates the intent of Ajax. Ajax isn't just about sending asynchronous events, it's also about sending only what I need and receiving only what I need. Sending back the entire modelstate in order to provide error details doesn't seem to go with Ajax.

我正在考虑的是进行客户端验证,但服务器代码和自定义viewmodel可以用于告诉客户端如何动态创建验证规则。

What I'm thinking about doing is having client-side only validation, but that server code and a custom viewmodel can be used to tell the client how to dynamically create those validation rules.

我也怀疑IronRuby或IronPython这样的动态语言可能会提供更优雅的方式来解决这些问题,但在我研究这种可能性之前可能会稍长一些

I also suspect that a dynamic language like IronRuby or IronPython might offer a more elegant way to solve these problems, but it could be a little longer before I look into that possibility.

推荐答案

如果我明白你正在努力做什么,我的第一个答案是否定的,你不能使用模型状态因为它是通过和Ajax请求。
也许你可以模仿ModelState行为来显示错误:

If i understand right what you are trying to do, my first answer will be no, you cannot use the model state as it is through and Ajax request. Maybe you can emulate the ModelState behavior, to display the errors:


  1. 传递一个通过JSON列出< KeyValuePair< string,string>> (属性,消息)(这将要求您将modelState从modelState传递给新结构),并执行验证摘要的HTML构造通过JS / jQuery(我认为是杀死解决方案)。

  1. Passing a List<KeyValuePair<string,string>> (property,message) by JSON (this will require you to pass the modelErrors form the modelState to the new structure) and do the HTML construction of a Validation Summary by JS/jQuery (which i think is over killing solution).

如果你要去服务器,只有做一个渲染部分的 Html.ValidationSummary(),将其传递给JSON并将其添加到表单中。如果一切正常,只需返回PartialDetails视图并替换实际内容。这将需要某种状态参数,以便您知道从ajax回调服务器返回的内容。

If you are going to the server, and there are any errors just do a render partial of the Html.ValidationSummary(), pass it through JSON and prepend it to the form. If everything was OK, just return the PartialDetails view and replace the actual content. This will require some kind of status parameter so you know what is coming back from the server on the ajax callback.

编辑:这最后一个选项听起来不错,但很棘手,因为您需要通过JSONResult返回一个字符串形式的部分视图,这里有一个关于这个hack的问题和解决方案将视图呈现为字符串

This last option sounds good but tricky, because you will need to return a partial View in a string form by JSONResult, here is a question and solution about that hack Render a view as a string.

个人而言, t认为使用错误属性将会做任何事情,我只是使用它到非常具体的情况,如超时错误,服务器异常,而不是应用程序例外。

Personally, i don't think that using the error attribute will do any good at all, i just use it to very specific situations like timeout errors, and server exceptions, not app exceptions.

编辑:
使用JSON

Using JSON

[AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(int id, FormCollection formValues)
        {
            Dinner dinner = dinnerRepository.GetDinner(id);
            try
            {
                UpdateModel(dinner);
                dinnerRepository.Save();
                return Json(new 
                {
                    result = "success",
                    html = this.RenderToString("PartialDetails", dinner) 
                });

            }
            catch
            {
                foreach (var issue in dinner.GetRuleViolations())
                {
                    ModelState.AddModelError(issue.PropertyName, issue.ErrorMessage);
                }
                return Json(new
                {
                    result = "failed",
                    html = this.RenderToString("PartialEdit", dinner)
                });
            }
        }

这里结果参数会让你知道采取什么行动在每种情况下,只需要在回调中检查它。

Here the result parameter will let you know what action to do in each case, just have to check it on the callback.

这篇关于在ASP.Net MVC中,ModelState可以与ajax更新一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆