How to determine postback with javascript and asp.net mvc?
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 a开发者_Go百科gain 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;
}
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>
<%
}
%>
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
精彩评论