在ASP.Net MVC 3个正确的方式来处理Ajax调用正确、方式、Net、ASP

2023-09-10 15:55:31 作者:冷暖自知

在编码了阿贾克斯在ASP.Net MVC调用我们有很多选择,只要发出呼叫,处理它们的服务器上,并处理客户机上的成功和失败。有些东西显然有一个正确的答案,但我一直无法找到明确的指导。因此,终端到终端的,什么是正确的方法,使Ajax调用?

When coding up Ajax calls in ASP.Net MVC we have a lot of options as far as issuing calls, handling them on the server, and dealing with successes and failures on the client. Some things clearly have a correct answer, but I've been unable to find clear-cut guidance. So, end-to-end, what is the correct way to make an ajax call?

什么是对URL的动作URL注入Ajax调用的最好方法? 出于何种考虑选择JsonBehavior时候? 什么是处理在服务器端错误的最好方法是什么? 如果客户端错误()回调被任何错误触发(即意外OutOfMemoryException异常),或者仅由可预见的错误(如输入无效)? 这是在一个方法的错误()回调将触发出口误差的最佳方式。 确保错误回调最佳的方式得到正确的状态code和响应文本。 如果验证错误导致的错误状态code或他们应该是一个响应验证对象的一部分。 What is the best way to inject the url of the action for the url into the ajax call? What are the considerations when choosing JsonBehavior? What is the best way to handle errors on the server side? Should the client side error() callback be triggered by any errors (ie unexpected OutOfMemoryException), or only by foreseeable errors (ie invalid input)? What is the best way of exporting errors in a way that the error() callback will be triggered. Best way of ensuring the error callback gets the correct status code and response text. Should validation errors result in an Error StatusCode or should they be part of a responding validation object. 应该预料的错误服务器端被显示在一个类似的方式验证摘要?也许只是'的东西,去-错误'对话?如果客户能够在两者之间进行区分?

任何其他事情的人有强烈的意见?

Any other things people have strong opinions on?

推荐答案

什么是注入的网址进入了阿贾克斯的动作URL呼叫的最佳方法是什么? 有没有这个公约,这也很大程度上取决于如何您的内容已经给客户端。通过意见/局部视图(在这种情况下,你可能会产生与 HTML / 网​​址辅助方法或者是它的网址是它客户端(模板等等)在纯粹的产生。这是很常见的,我们只是需要一些常用的HTML元素与阿贾克斯的行为扩展(如表格,按钮和链接)。在这种情况下,最好提供,我们还可以读取正确的URL从他们身上,并利用它们在我们的脚本(如的href 中的链接)。它也更清楚用户里的东西都指向。无论我们将它们转换为GET / POST / DELETE / PUT请求并没有真正的问题了。我建议,以避免硬编码的URL在你的脚本,因为你可能会改变路由或者提供加工等手段,通过使用 HTML 助手在可能的情况是在维护方面一个更好的方法。将URL添加元素不会自动支持他们(没有的href SRC 属性),你可以随时将其添加为自定义属性尤其是当你使用数据属性(如数据的href 或类似)。阅读约翰Resig的博客帖子这些。

Question/Answer style

What is the best way to inject the URL of the action for the URL into the Ajax call? There's no convention about this and it also largely depends how your content has been brought to the client. Was it via views/partial views (in which case you could generate URLs with Html/Url helper methods or is it purely generated on the client (templating and such). It's quite common that we just want some usual HTML elements to extend with Ajax behaviour (like forms, buttons and links). In this situation it's best to provide correct URLs that we can also read from them and use them in our scripts (like href in links). It's also more clear to users where things are pointing to. Whether we convert them to GET/POST/DELETE/PUT requests doesn't really matter any more. I would suggest to avoid hard-coding URLs in your scripts because you may change routing or provide other means of processing. By using Html helpers wherever possible is a much better way in terms of maintenance. When adding URLs to elements that don't support them automatically (no href or src attribute) you can always add them as custom attributes especially when you use data attribute (like data-href or similar). Read John Resig's blog post about these.

出于何种考虑选择JsonBehavior时候? 这是最好的时候,你必须返回JSON进行POST请求。在GET请求,你必须知道可能产生的影响 JSON劫持这也是为什么你必须明确指定你允许获得使用JSON结果的请求的原因。

What are the considerations when choosing JsonBehavior? It's best to make POST requests when you have to return Json. In GET requests you have to be aware of the possible implications JSON Hijacking that's also the reason why you have to explicitly specify that you allow get requests with JSON results.

什么是处理在服务器端错误的最好方法是什么? 处理服务器错误的最佳方法(即不能,不应该燮pressed)是实际通知用户出现错误。它的细节通常并不重要,因为用户不开发精明,但告诉他们出事了就可以了。特别是如果你可以为他们提供某种形式的解决方案中。而使用Ajax调用它的赌注返回错误,可以与错误处理程序的Javascript功能来处理错误。我写了一个博客文章,详细描述了整个过程也提供了code,它展示了如何正确处理验证错误。我个人认为返回错误的成功是错误的。所以我不知道。但是,这是议论文。

What is the best way to handle errors on the server side? The best way to process server errors (that can't and shouldn't be suppressed) is to actually inform the user of the error. Details of it are usually not important since users are not development savvy but telling them something went wrong is ok. Especially if you can offer them some sort of a solution. And with Ajax call it's bets to return errors as errors that can be handled with error handler Javascript functions. I've written a blog post that details the whole process and also provides the code that shows how to correctly handle validation errors. I personally think that returning errors as success is wrong. hence I don't. But that's argumentative. My controller actions are rather simplified by the code I use:

[HandleModelStateException]
public ActionResult AddUser(User user)
{
    if (!this.ModelState.IsValid)
    {
        throw new ModelStateException(this.ModelState);
    }
    // process valid data
}

如果客户端错误()回调被任何错误触发(即意外 OutOfMemoryException异常),或者仅由可预见的错误(如输入无效) 正如previously错误,应该向用户报告时,他们会得到意想不到的结果从他们开始。做到这一点,应当报他们不要燮preSS的错误。但是,不要走太多的细节。内存不够的异常是有点太复杂,解释屠通常计算机用户。报告的东西对人友好的和短期。

Should the client side error() callback be triggered by any errors (ie unexpected OutOfMemoryException), or only by foreseeable errors (ie invalid input)? As stated previously errors should be reported to users when they will get unexpected results from what they initiated. Don't suppress errors that should be reported to them. But don't go into too much detail. Out of memory exception is a bit too complex to explain tu usual computer users. Report something human friendly and short.

什么是一种方式,错误()回调将会触发输出错误的最好方法。 看看我的博客文章并检查code看如何创建由错误()函数处理错误

What is the best way of exporting errors in a way that the error() callback will be triggered. Look at my blog post and check the code to see how to create errors that are handled by the error() function

在保证错误回调的最好的方式得到正确的状态code和响应文本。 同样博客帖子

Best way of ensuring the error callback gets the correct status code and response text. Same blog post

如果验证错误导致一个错误状态code 或他们应该是一个响应验证对象的一部分。 验证错误实际上由自然界的警告,应作这样的处理。这就是为什么你可以看到一些网站的时候数据是有效的,而不是他们做了另一个错误只是告知用户也报告积极表单验证模式。验证错误通常是植根于无效的用户界面体验和信息不足。

Should validation errors result in an error StatusCode or should they be part of a responding validation object. Validation errors are actually warnings by nature and should be treated as such. That's why you can see positive form validation pattern on some sites that also report when data is valid instead of just informing users that they've made yet another mistake. Validation errors are usually rooted in invalid user interface experience and insufficient information.

什么是处理在客户端错误的最好方法是什么? 这在很大程度上取决于你的应用程序,但我建议你遵循成熟的模式,因为用户很可能的知道该怎么做的,不会混淆。为什么你认为OpenOffice的使用几乎相同的用户界面为微软的Office?因为用户知道它是如何工作的,因此更容易被与应用程序的快速,轻松地熟悉。但是,如果你可以,不要把用户作为哑人。使用积极的验证。一些错误也应显示为错误。哦。顺便说一句。我在我的应用程序,其中的信息,如成功运作报告给用户,但不会打扰他们的工作中使用不引人注目的相关信息。这一段时间后会自动消失。类似于Gmail不会。它只是通知您的邮件已发送这种信息不需要任何确认。 jQuery的阿贾克斯()载体作用支持成功和错误的功能,所以明智的做法是同时使用。还是那句话:返回错误,成功是不正确的。我们不需要比所有的错误功能。我HandleModelState行动过滤器返回特别400错误code错误,可以使用,它的结果也是如此。

What is the best way to handle errors on the client side? This largely depends on your application but I suggest you follow proven patterns because users are likely to know the drill and won't confuse them. Why do you think OpenOffice uses almost identical UI as Microsoft Office? Because users know how it works so it's more likely to be acquainted with the app fast and painlessly. But if you can, don't treat users as dumb people. Use positive validation. Some errors should also be displayed as errors. Oh. Btw. I use unobtrusive infos in my app where information such as successful operation is reported to users but doesn't intrude their work. It automatically disappears after a while. Similar to what GMail does. It just informs you that mail has been sent and this info doesn't need any confirmation. jQuery ajax() functin supports success and error functions, so it's wise to use both. Again: Returning errors as success is not right. We wouldn't need error functions than at all. My HandleModelState action filter returns errors with particular 400 error code that can be used and its result as well.

$.ajax({
    url: $(this).attr("href"),
    data: someDataObj,
    type: "POST",
    success: function(data){
        // process data
    },
    error: function(xhr, status, err){
        if (xhr.status = 400) {
            // handle my error in xhr.resposeText
        }
        else {
            // handle other errors that are cause by unknown processing
        }
    }
});

如果发生意外错误服务器端显示在一个类似的方式验证摘要?也许只是的东西,去-错误的对话?如果客户能够在两者之间进行区分? 人们不喜欢大红色警报。如果事情是一个警告的性质应该比实际的错误被视为友善的prevent您的应用程序正常工作。验证尤其应该很友好。错误应该由用户进行确认,警告也许不应该。取决于它们的性质。但是,如果他们应该那么他们很可能错误。

Should unexpected errors server-side be displayed in a similar way as the validation summary? Maybe a just "something-went-wrong" dialog? Should the client be able to distinguish between the two? People don't like the big red alerts. If something is a warning by nature it should be treated friendlier than actual errors that prevent your app to work properly. Validation in particular should be very friendly. Errors should be confirmed by users, warnings maybe shouldn't. Depends on their nature. But if they should be then they're probably errors.

我希望这将清除一些东西给你。

I hope this clears some things for you.