Wednesday, 16 January 2013

ASP.NET MVC Razor IsPost property with IF –Else loop

ASP.NET MVC Razor a new view engine from Microsoft  looks very promising. Here are example of code where we can determine page is post back or not. It support a IsPost Property which will tell you whether page is post back or not. So based on that we can write code for handling post back.  Also one of greatest feature of razor is we can write code for decision making  like if else and other stuff with single @ statement isn’t that great stuff.
Here is the stuff how we can write the code with IsPost property.
?
1
2
3
4
5
6
7
8
9
10
11
@{
     var Message="";
     if(IsPost)
      {
            Message ="This is from the postback";
      }
       else
    {
            Message="This is without postback";
    }
}
And we can now print that variable with following HTML Form.
?
1
2
3
4
<form method="POST" action="" >
<input type="Submit" name="Submit" value="Submit"/>
<p>@Message</p>
</form>
here submit button will submit the form and based on that it will print message. Let’s see how it looks in browser before post back and after post back.
WithoutPostback
And After post back
AfterPostaback

No comments:

Post a Comment