Mou
Mou

Reputation: 16292

ASP.Net MVC: Why only selected value is getting passed to action when form submit

I am trying to get control over it.just see the view and controller code

<form id='your-form' action='@Url.Action("Action","Controller")' method='post'>
     <b>Gender</b><br />
     <input type='radio' name='gender' value='Male' /> Male <br />
     <input type='radio' name='gender' value='Female' /> Female <br />
     <hr />
     <b>Hobbies</b><br />
     <input type='checkbox' name='hobbies' value='Reading' /> Reading <br />
     <input type='checkbox' name='hobbies' value='Sports' /> Sports <br />
     <input type='checkbox' name='hobbies' value='Movies' /> Movies <br />
     <input type='submit' value='Update Profile' />
</form>

public class HomeController : Controller
{  
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(string gender, string[] hobbies)
        {
            // Example output 
            var output = String.Format("The user's gender is <b>{0}</b> and they enjoy <b>{1}</b>", gender, String.Join(",", hobbies));
            return Content(output);
        }
}

just see and tell me when user select one or two hobbies out of 3 then why only selected hobbies is getting post back to action method and will stored in hobbies array.

why not all hobbies is getting posted to action with selected hobbies indication?

Upvotes: 2

Views: 100

Answers (2)

Becuzz
Becuzz

Reputation: 6866

Because that is how form encoding a form works. When the browser makes a POST request to your website, the body looks something like this:

gender=Male&hobbies=Reading&hobbies=Movies

MVC just takes that and shoves it in some variables for you. You assume that any hobbies that didn't come back in the hobbies array weren't selected.

Upvotes: 4

user3559349
user3559349

Reputation:

Unchecked checkboxes (and radio buttons) do not post back a value because they are not considered Successful controls.

And in your case it would not make sense to do so since if they did, string[] hobbies would contain an array of all hobbies and you would have no way of determining which ones the user selected.

Upvotes: 1

Related Questions