HttpGet and HttpPost Attributes Example in ASP.Net MVC

Last Reply 3 months ago By dharmendr

Posted 3 months ago

Below there are 2 create methods.

Why they have used 2nd create method and they have used HttpPost for that ?

What is the need of 2 methods ?

I have the Below code:

        public ActionResult Create()
        {
            return View();
        }

        // POST: Movies/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "ID,Title,ReleaseDate,Genre,Price")] Movie movie)
        {
            if (ModelState.IsValid)
            {
                db.Movies.Add(movie);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(movie);
        }

 

You are viewing reply posted by: dharmendr 3 months ago.
Posted 3 months ago

Hi chetan,

HttpGet and HttpPost are both the methods of posting client data or form data to the server. HTTP is a HyperText Transfer Protocol that is designed to send and receive the data between client and server using web pages.

HTTP has two methods that are used for posting data from web pages to the server. These two methods are HttpGet and HttpPost.

HttpPost is only useful when you are passing sensitive information to the server.

As per your example there are two versions of Create method, one that renders the Create form and the other that handles the request when that form is posted or submitted.

Difference between HttpGet and HttpPost Method

1. HttpGet method is default whereas you need to specify HttpPost attribute if you are posting data using HttpPost method.

2. HttpGet method creates a query string of the name-value pair whereas HttpPost method passes the name and value pairs in the body of the HTTP request.

3. HttpGet request has limited length and mostly it is limited to 255 characters long whereas HttpPost request has no maximum limit.

4. HttpGet is comparatively faster than HttpPost. HttpPost takes extra time in encapsulating the data.

5. HttpGet can carry only string data whereas HttpPost can carry both string and binary data.

6. HttpGet method creates readable url so it can be cached and bookmarked whereas such facility is not available in HttpPost method.

Refer below article for example.

ASP.Net MVC: Form Submit (Post) example