2

I am currently using ASP.NET MVC2 and I have a ActionController that allows me to save only if the form content is valid, something like

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);
}

This occasion that, if I'm completing incorrectly the editing form it shows again repeatedly.

My question is if I can trust in the following piece of javascript code to determine whether a call is a PostBack, in other words if it helps me to know it's not the first time that I'm visiting that page. I read somewhere that I should not trust in document.referrer because some proxies delete it, then what code should I use?

function isPostBack() {
    if (document.referrer != null && document.referrer == window.location.href)
        return true;
    return false;
}
1
  • 1
    i have no idea what your asking. there is no "postback" in MVC (thankfully). There is a GET (first time), or POST (submit). What are you trying to achieve? Commented Dec 21, 2010 at 8:42

2 Answers 2

2

This code could be easily hacked by malicious user or Javascript could be disabled at all.

I don't know exactly your requirements, but I would probably prefer server side check during view rendering. So instead of

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

I would use

<% 
    if (Request.HttpMethod == "POST") 
    {
%>
    <script type="text/javascript">
        alert("Check your data!");
    </script>
<% 
    }
%>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for responding, but unfortunately I need a client-side check because I have to include this function (IsPostBack) within a file. js, currently I do not know how to use the server code, as you propose, into a file. js, that could solve my problem. Thanks again.
0

You could expose a public property on your page :

public bool IsPostBack { get; set; }

Set this property to true / false by checking the !IsPostBack in your Codebehind and assign the value to a hidden variable on the page.

On the client side read the value fromt he hidden variable.

Hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.