Mvc3 value after submit

I have a form with two drop-down fields and a checkbox. Everything works for me correctly, but for some reason I can’t get the value of the flag, if it is checked, this is my code.

[HttpPost] public ActionResult view(string pick) { switch (pick) { case "Deny": // capture checkbox value here break; case "Accept": // capture checkbox value here break; } return View(); } 

This is my look

 @using (Html.BeginForm("view", "grouprequest", FormMethod.Post, new {})) { @Html.DropDownList("pick", new SelectList(new List<Object>{ new{ Text ="Accept", Value= "Accept"},new{ Text ="Deny", Value= "Deny"}}, "Value", "Text"), new {}) <input type="submit" name="work" id="work" value="Update" style="font-size:16px" /> foreach (var item in Model) { <input type="checkbox" id="@item.grouprequestID" name="@item.grouprequestID" value="@item.grouprequestID" /> } } 

Basically, in the drop-down list there are 2 options that Accept and Reject . I can write which user selects through the SWITCH-case to the controller now, how can I capture the value of the flags? If you notice that the flags have a variable named @groupRequestID , so each flag has a different unique value, for example, 1,2,3, etc. Any help would be greatly appreciated!

Model

  public class grouprequest { [Key] public int grouprequestID { get; set; } public int? profileID { get; set; } public int? registrationID { get; set; } public DateTime expires { get; set; } public int? Grouplink { get; set; } } 
+6
source share
1 answer

Flags when sent to the server are a little strange. If checked, the browser will send name=value , as in

 <input type="checkbox" name="name" value="value" /> 

But if the flag is not , the server does not send anything.

 <input type="checkbox" name="Check1" id="Checks1" value="Hello" checked="checked"/> <input type="checkbox" name="Check1" id="Checks1" value="Hello1" /> <input type="checkbox" name="Check1" id="Checks1" value="Hello2" /> 

The result is Check1 = Hello

What does this mean if all of your flags are connected, naming them the same way will fill the same attribute of your ActionMethod. If this attribute is an enumeration, it will contain only those that have been marked.

If you have this in your opinion:

 <input type="checkbox" name="MyValues" value="1" checked="checked"/> <input type="checkbox" name="MyValues" value="2" /> <input type="checkbox" name="MyValues" value="3" /> 

and this is like the action method of your controller:

 public ActionMethod MyAction(IEumerable<int> myValues) 

The myValues variable will look like this:

 myValues[0] == 1 

It should also be noted that if you use the helper extension Html :

 @Html.CheckBoxFor(m => m.MyValue) 

Where MyValue is a bool , the extension will create a checkbox input tag, as well as a hidden input tag with the same name, which means that the value will always be passed to the controller method.

Hope this helps.

+17
source

Source: https://habr.com/ru/post/950305/


All Articles