I am a NewBie for MVC3 and trying to create a Project in MVC 3 Razor…
So Facing Lot Many Problems and also solving them with the help of Google and few of my Expert Friends and MVP’s. So Thinking to make some Blog Posts for the people like me.
Today I was trying to access a html checkbox from the view at the controller as I have to make the decision on the bases of this checkbox if it is checked I need to delete the record else I have to process the record in different way. So my First concern was how can I get the checkbox at the controller.
The Answer Goes like:
I find Two Methods to solve this issue although I am not very much sure right now which one is better and why.
Points to keep in mind. We need to post back the form from the view (obviously because without post back we would not get the changes made by the user at the backend [Contoller]).
So in view I added the following line:
<form method="post" action="ControllerName">
This will post the form to the controller and now we need to create a controller which can handle this
Here the controller goes like
[HttpPost]
[ValidateInput(false)]
public ActionResult ControllerName(FormCollection collection)
{
if ( collection["chk"]!= null)
{
//delete from session here
}
return View(p);
}
I have used HttpPost to mark this controller that it will handle the post back as far as I have googled I found that [AcceptVerbs(HttpVerbs.Post)] and [HttpPost] are same make (me correct if I am wrong) and now here we can access the checkbox here “chk” is the name of the checkbox I have created in the view. If the condition is false that means if the collection[“chk”] is null that means the checkbox is not selected and if the condition is false that is collection[“chk”] is not null that means the checkbox is selected. I have used [ValidateInput(false)] because I don’t want to validate the form inputs at the time of postback you can skip this line it won’t make much effect.
In the second way we need to change the controller a bit in the above example we are passing the formcollection here we will use the request. Just peep into the code
[HttpPost]
[ValidateInput(false)]
public ActionResult ControllerName()
{
if ( Request["chk"]!= null)
{
//delete from session here
}
return View(p);
}
The only change I made is that instead of using the formcolletion I am using the request which already contain the formcollection.
Thanks For Reading this Article. Will try to post more articles on MVC 3.
0 comments:
Post a Comment