javascript - 如何确定回发与javascript 和asp.net mvc?

标签 javascript jquery asp.net-mvc

我目前正在使用 ASP.NET MVC2,并且我有一个 ActionController,它允许我仅在表单内容有效时才进行保存,例如

public ActionResult Edit(Guid id)
{
    //....
    return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Guid id, DTOUserEdit dto)
{
    if ( ModelState.IsValid) Save(user);
    return ModelState.IsValid ? RedirectToAction("Index") : (ActionResult)View(dto);
}

这次,如果我没有正确填写编辑表单,它会再次重复显示。

我的问题是,我是否可以相信以下一段 javascript 代码来确定调用是否为 PostBack,换句话说,它是否可以帮助我知道这不是我第一次访问该页面。我在某处读到我不应该信任 document.referrer 因为一些代理删除了它,那么我应该使用什么代码?

function isPostBack() {
    if (document.referrer != null && document.referrer == window.location.href)
        return true;
    return false;
}

最佳答案

此代码很容易被恶意用户破解,或者 Javascript 可能完全被禁用。

我不太清楚您的要求,但我可能更喜欢在 View 渲染期间进行服务器端检查。所以不是

<script type="text/javascript">
    if (isPostBack())
    {
        alert("Check your data!");
    }
</script>

我会用

<% 
    if (Request.HttpMethod == "POST") 
    {
%>
    <script type="text/javascript">
        alert("Check your data!");
    </script>
<% 
    }
%>

关于javascript - 如何确定回发与javascript 和asp.net mvc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4495375/

相关文章:

java - 重用 servlet 生成的图像

javascript - 类型错误 : Cannot read property '$auth' of undefined Vuejs

asp.net-mvc - 在 MVC2 中使用 FluentValidation 与 CaSTLe Windsor 和 Entity Framework 4.0 (POCO)

javascript - Bootstrap 导航栏在移动设备上无法关闭

javascript - Google Apps 脚本 : strange "Missing ; before statement." error

jquery - 如何将jquery Mustache应用到外部文件/模板

jquery - 发送 json 到服务器 spring 3.x

javascript - 无法从 jQuery 函数返回 JSON 对象

c# - 如何在 Html.Editor 中直接加载 Object additionalViewData 的值?

html - 检测手机与非电话移动设备?