RSS

ViewBag vs TempData vs Session

ViewData

  1. ViewData is a dictionary object that is derived from ViewDataDictionary class.
    1. public ViewDataDictionary ViewData { get; set; }
  2. ViewData is a property of ControllerBase class.
  3. ViewData is used to pass data from controller to corresponding view.
  4. It’s life lies only during the current request.
  5. If redirection occurs then it’s value becomes null.
  6. It’s required typecasting for getting data and check for null values to avoid error.

ViewBag

  1. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  2. Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
    1. public Object ViewBag { get; }
  3. ViewBag is a property of ControllerBase class.
  4. It’s life also lies only during the current request.
  5. If redirection occurs then it’s value becomes null.
  6. It doesn’t required typecasting for getting data.

TempData

  1. TempData is a dictionary object that is derived from TempDataDictionary class and stored in short lives session.
    1. public TempDataDictionary TempData { get; set; }
  2. TempData is a property of ControllerBase class.
  3. TempData is used to pass data from current request to subsequent request (means redirecting from one page to another).
  4. It’s life is very short and lies only till the target view is fully loaded.
  5. It’s required typecasting for getting data and check for null values to avoid error.
  6. It is used to store only one time messages like error messages, validation messages. To persist data with TempData refer this article: Persisting Data with TempData

Session

  1. In ASP.NET MVC, Session is a property of Controller class whose type is HttpSessionStateBase.
    1. public HttpSessionStateBase Session { get; }
  2. Session is also used to pass data within the ASP.NET MVC application and Unlike TempData, it persists for its expiration time (by default session expiration time is 20 minutes but it can be increased).
  3. Session is valid for all requests, not for a single redirect.
  4. It’s also required typecasting for getting data and check for null values to avoid error.
Advertisements
 
Leave a comment

Posted by on August 7, 2017 in .NET, ASP.NET, MVC

 

Data Annotations

routes.MapRoute(
name: “Default”,
url: “{controller}/{action}/{id}”,
defaults: new { controller = “myuser”, action = “Index”, id = UrlParameter.Optional }
);

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.ComponentModel.DataAnnotations.Schema;

[Required]
[StringLength(20, MinimumLength = 4, ErrorMessage = “Must be at least 4 characters long.”)]
[Remote(“checkusername”, “myuser”)]
public string username { get; set; }

[Required]
public string firstname { get; set; }

public string lastname { get; set; }

[Required]
public string address { get; set; }

[Required]
[DataType(DataType.PhoneNumber)]
[StringLength(10, MinimumLength = 10, ErrorMessage = “{0}: it should be 10 digits”)]
public Nullable phone { get; set; }

[Required(ErrorMessage = “{0} required”)]
[DataType(DataType.EmailAddress)]
[Display(Name = “Email”)]
[RegularExpression(@”\w+([-+.’]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*”, ErrorMessage = “Invalid email”)]
[Remote(“checkemail”, “myuser”, ErrorMessage = “Already in use!”)]
[StringLength(100, ErrorMessage = “{0}: 100 is the limit”)]
public string email { get; set; }

public Nullable isactive { get; set; }

[Required]
[DataType(DataType.Password)]
public string password { get; set; }

[Required]
[NotMapped]
[System.ComponentModel.DataAnnotations.Compare(“password”, ErrorMessage = “Password doesn’t match.”)]
[DataType(DataType.Password)]
public string confirmpassword { get; set; }

public JsonResult checkusername(string username)
{
var data = db.users.Where(p => p.username.Equals(username, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

if (data != null)
{
return Json(“Sorry, this name already exists”, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}

public JsonResult checkemail(string email)
{
var result = true;
var user = db.users.Where(x => x.email == email).FirstOrDefault();

if (user != null)
result = false;

return Json(result, JsonRequestBehavior.AllowGet);
}

 
Leave a comment

Posted by on October 31, 2016 in .NET

 

Difference between GET and POST

Both perform same action only. Using both we can able to transfer data from one application to another. Using get method we can able to view the information in URL itself, but using post we can able to transfer data over networks, so this is very secure. Post method data we can’t get it directly. But Get method data we can get easily.

We can’t able to transfer bulk of data using GET method. But using post method we can able to transfer bulk of data. Compare to GET method POST method is secure.

 
Leave a comment

Posted by on August 18, 2016 in .NET

 

Self-join queries

Self-Join is a type of join which is used to join the same table by creating the second instance of the same table. So we join 2 instances of the same table in case of self-join. This type of join is used when there is the requirement to get the referenced data which is available in the same table.
e.g. A table contains EmpId, Ename and ManagerId
As the manager id is also an employee id. Now if we want that who is the manager of which employee. In this situation, we need to create the instance of the same table and get the required data as:

SELECT EMPID, ENAME, ENAME AS [MANAGER NAME]
FROM EMP E1, EMP E2
WHERE E1.EMPID= E2.MANAGERID

 
Leave a comment

Posted by on August 18, 2016 in .NET

 

Anonymous methods in C#

The concept of anonymous method was introduced in C# 2.0. An anonymous method is inline unnamed method in the code. It is created using the delegate keyword and doesn’t required name and return type. Hence we can say, an anonymous method has only body without name, optional parameters and return type. An anonymous method behaves like a regular method and allows us to write inline code in place of explicitly named methods.

A Simple Anonymous Method Example

delegate int MathOp(int a, int b);
class Program
{
   //delegate for representing anonymous method
   delegate int del(int x, int y);
 
static void Main(string[] args)
{
   //anonymous method using delegate keyword
   del d1 = delegate(int x, int y) { return x * y; };
 
   int z1 = d1(2, 3);
   Console.WriteLine(z1);
}
}
//output:
6

Key points about anonymous method

  1. A variable, declared outside the anonymous method can be accessed inside the anonymous method.
  2. A variable, declared inside the anonymous method can’t be accessed outside the anonymous method.
  3. We use anonymous method in event handling.
  4. An anonymous method, declared without parenthesis can be assigned to a delegate with any signature.
  5. Unsafe code can’t be accessed within an anonymous method.
  6. An anonymous method can’t access the ref or out parameters of an outer scope.

Anonymous Method as an Event Handler

 <form id="form1" runat="server">
 < div align="center">
<h2>Anonymous Method Example</h2>
 <br />
 <asp:Label ID="lblmsg" runat="server" ForeColor="Green" Font-Bold="true"></asp:Label>
 <br /><br />
 <asp:Button ID="btnSubmit" runat="server" Text="Submit" /> 
 <asp:Button ID="btnCancel" runat="server" Text="Cancel" />
 </div>
 </form>

protected void Page_Load(object sender, EventArgs e)
{
   // Click Event handler using Regular method
   btnCancel.Click += new EventHandler(ClickEvent);
   // Click Event handler using Anonymous method
   btnSubmit.Click += delegate { lblmsg.Text=
          "Submit Button clicked using Anonymous method"; };
}
protected void ClickEvent(object sender, EventArgs e)
{
   lblmsg.Text="Cancel Button clicked using Regular method";
}

 
Leave a comment

Posted by on August 18, 2016 in .NET

 

Stored procedure vs inline query

Stored procedures are precompiled and cached so the performance is much better.

The choice of choosing stored procedures will not be performance but it will be more from the aspect of security and maintenance. Below are some of the points where stored procedures are definitely a plus over inline SQL.

Abstraction

By putting all your SQL code into a stored procedure, your application is completely abstracted from the field names, tables names, etc. So when you make changes in the SQL, you have less impact in your C# code.

Security

This is the best part where stored procedures again score, you can assign execution rights on users and roles.

Maintenance ease

Now because we have centralized our stored procedures any issue like fixing defects and other changes can be easily done in a stored procedure and it will be reflected across the installed clients. At least we do not need to compile and deploy DLLs and EXEs.

Centralized tuning

If we know we have a slow running stored procedure, we can isolate it and the DBA guys can performance tune it separately.

Cursors, temp table complications

Simple TSQLs are OK. But what if you have a bunch of statements with IF, ELSE, Cursors, etc? For those kind of scenarios, again stored procedures are very handy.

 
Leave a comment

Posted by on August 8, 2016 in .NET

 

State management

A new instance of the Web page class is created each time the page is posted to the server. In traditional Web programming, this would typically mean that all information associated with the page and the controls on the page would be lost with each round trip.

To overcome this inherent limitation of traditional Web programming, ASP.NET includes several options. These features are as follows:

  • View state
  • Control state
  • Hidden fields
  • Cookies
  • Query strings
  • Application state
  • Session state
  • Profile Properties

 

https://msdn.microsoft.com/en-us/library/75x4ha6s.aspx

 
Leave a comment

Posted by on August 6, 2016 in .NET

 
 
%d bloggers like this: