Bind Checkboxes to int array/enumerable in MVC - asp.net-mvc-3

#Html.CheckBox("orderNumbers", new { value = 1 })
#Html.CheckBox("orderNumbers", new { value = 2 })
#Html.CheckBox("orderNumbers", new { value = 3 })
#Html.CheckBox("orderNumbers", new { value = 4 })
#Html.CheckBox("orderNumbers", new { value = 5 })
[HttpPost]
public ActionResult MarkAsCompleted(IEnumerable<int> orderNumbers) { }
[HttpPost]
public ActionResult MarkAsCompleted(IEnumerable<string> orderNumbers) { }
If I use the first signature in my action method, I get an empty IEnumerable.
If I use the second signature I do receive the values but I also receive a false value for the unselected values (because of MVCs pattern of shadowing all checkboxes with a hidden field).
e.g. I will receive something like orderNumbers = { "1", "2", "false", "4", "false" }
Why can't I just get the list of numbers?

You can get all the checked values by the following way.
Controller code :
public ActionResult Index()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string[] orderNumbers)
{
return View();
}
View Code :
#using (Html.BeginForm())
{
<input name="orderNumbers" type="checkbox" value="1" />
<input name="orderNumbers" type="checkbox" value="2" />
<input name="orderNumbers" type="checkbox" value="3" />
<input name="orderNumbers" type="checkbox" value="4" />
<input name="orderNumbers" type="checkbox" value="5" />
<input type="submit" name="temp" value="hi" />
}
Please keep one thing in my mind that, you need to give same name to all checkboxes. In array you will get values for all checked checkboxes.

Because thats how the provided CheckBoxFor helper is working.
You have to generate the html for the checkboxes yourself. Then the hidden inputs are not generated and you will get only the selected integer values.

In addition to alok_dida's great answer. Since all the values are integers, you can have your controller code take an array of integers and avoid doing the conversion yourself.
This works in MVC4+:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(int[] orderNumbers)
{
return View();
}

Related

Post HiddenField values to controller with model .net core 6

var tags = M.Chips.getInstance($('.chips')).chipsData;
var sendTags = JSON.stringify(tags, null, 2);
$('#Tags').val(sendTags);
with the above method I stored chips data to hiddenfileds with .onSubmit() method. But at controller level, couldn't get them.
I'am expecting hiddenfiled chips data at contorller level along with other model property.
But at controller level, couldn't get them.
If you want to get the hiddenfileds, I have a suggestion like below:
You can create a hidden input, and use name attribute to bind the data.
<input id="Tags" name="tags" type="hidden" />
The demo like below, you can refer to it:
Privacy view:
<form asp-action="Privacy" method="post">
<input id="Tags" name="tags" type="hidden" />
<input type="submit" value="submit"/>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
var tags = {
'x1': 1,
'x2': 2
}
var sendTags = JSON.stringify(tags, null, 2);
$('#Tags').val(sendTags);
</script>
Controller:
public IActionResult Privacy()
{
return View();
}
[HttpPost]
public IActionResult Privacy( string tags )
{
return View();
}
result:

How to use hidden field values from view to controller in asp.net mvc 3

I have to pass hidden filed values to controller action. So I have tried in the following way, but I am getting null values.
I have tried both methods i.e formcollection and viewmodel concept
Controller
public ActionResult MapIcon()
{
Hidden hd = new Hidden();
return View(hd);
}
[HttpPost]
public ActionResult MapIcon(Hidden hidden)
{
var value=hidden.hiddevalue;//null
FormCollection col = new FormCollection();
var value = col["hidden1"];
// string value = mycontroler.ControlName;
return View(hidden);
}
View
#model SVGImageUpload.Models.Hidden
Razor view:#using (Html.BeginForm(new { id = "postform" }))
{
<input type="hidden" id="" value="7" name="hidden1" />
<input type="hidden" id="" value="7" name="hidden2"/>
<input type="submit" value="Match"/>
}
Viewmodel
public class Hidden
{
public string hiddevalue { get; set; }
}
Try this, In Razor view:
#using (Html.BeginForm(new { id = "postform" }))
{
#Html.HiddenFor(m=>m.hiddevalue)
<input type="submit" value="Match"/>
}
It seems to me like you are trying to get multiple values into the POST controller. In that case, and by your exam, the value from the hidden input is enough. In that case, you can setup your controller as so:
public ActionResult Index()
{
Hidden hd = new Hidden();
return View(hd);
}
[HttpPost]
public ActionResult Index(IEnumerable<string> hiddens)
{
foreach (var item in hiddens)
{
//do whatter with item
}
return View(new Hidden());
}
and as for your view, simple change it in order to bind to the same name "hiddens" as so:
#using (Html.BeginForm(new { id = "postform" }))
{
<input type="hidden" value="7" name="hiddens" />
<input type="hidden" value="2" name="hiddens" />
<input type="submit" value="Match" />
}
Hope this serves what you are looking forward to.
if your hidden value is static.Than try this
View
#using (Html.BeginForm(new { id = "postform" }))
{
#Html.HiddenFor(m=>m.hiddevalue)
<input type="hidden" id="" value="7" name="hidden1" />
<input type="hidden" id="" value="7" name="hidden2"/>
<input type="submit" value="Match"/>
}
Controller
[HttpPost]
public ActionResult MapIcon(Hidden hidden, string hidden1, string hidden2)
{
var hiddenvalue = hidden.hiddevalue;
var hiddenvalue1 = hidden1;
var hiddenvalue2 = hidden2;
var value=hidden.hiddevalue;//null
FormCollection col = new FormCollection();
var value = col["hidden1"];
// string value = mycontroler.ControlName;
return View(hidden);
}
Script
$(document).ready(function () {
$('#hiddevalue').val("Jaimin");
});

mvc3 checkbox value after submit

I have a form with 2 fields a dropdownlist and a checkbox. I have everything working correctly but i can not for some reason obtain the value of a checkbox 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 view
#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 the dropdownlist has 2 options which are Accept and Deny I can capture which one the user chooses via the SWITCH-case in the controller now how can I capture the value of the checkboxes? If you notice the Checkboxes have a variable to them named #groupRequestID so every checkbox has a different unique value like 1,2,3 etc.. any help would be greatly appreciated !!
The 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; }
}
Check boxes when posted to the server act a little strange.
If a box is checked the browser will send name=value as in
<input type="checkbox" name="name" value="value" />
But if the checkbox is not checked the server doesn't 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" />
Will result in Check1 = Hello
What this means is if all your check boxes are related, naming them the same will populate the same attribute of your ActionMethod. If that attribute is an enumeration it will contain only the ones that are checked.
If you have this in your view:
<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 as your controller action method:
public ActionMethod MyAction(IEumerable<int> myValues)
The myValues variable will look like this:
myValues[0] == 1
You should also note that if you are using the Html helper extension:
#Html.CheckBoxFor(m => m.MyValue)
Where MyValue is a bool the extension will create a checkbox input tag and also a hidden input tag with the same name, meaning a value will always be passed into the controller method.
Hope this helps.

Using Html.RadioButtonFor with a boolean isn't writing Checked="Checked"

I am having an issue using the RadioButtonFor helper. When the value passed in is true, it isn't displaying a "check" in either radio button. When the value is false, it works just fine.
I copied this code from the project I am working on and created a sample application and I was able to replicate the issue. If I hard coded the value to true or false it seems to work, but when I use the "!string.IsNullOrEmpty(allgroups)" it doesn't.
From the View:
<div>
#Html.RadioButtonFor(m => m.AllGroups, true) All Groups
#Html.RadioButtonFor(m => m.AllGroups, false) Current Groups
</div>
From the ViewModel:
public bool AllGroups { get; set; }
From the Controller:
public ActionResult Index(string allgroups)
{
var model = new ProgramGroupIndexViewModel
{
AllGroups = !string.IsNullOrEmpty(allgroups)
};
return View(model);
}
From view source in IE:
<div>
<input id="AllGroups" name="AllGroups" type="radio" value="True" /> All Groups
<input id="AllGroups" name="AllGroups" type="radio" value="False" /> Current Groups
</div>
From view source when value of AllGroups is false (note it works):
<div>
<input id="AllGroups" name="AllGroups" type="radio" value="True" /> All Groups
<input checked="checked" id="AllGroups" name="AllGroups" type="radio" value="False" /> Current Groups
</div>
The model binding is getting confused because you named your action parameter the same as your model property. Change the name of your Index action parameter, and it should work.
public ActionResult Index(string showAllGroups)
{
var model = new ProgramGroup
{
AllGroups = !string.IsNullOrEmpty(showAllGroups);
};
return View(model);
}
if you are returning bool from model then there is no need to check uncheck explicitly mvc will do it itself just write
<div>
#Html.RadioButtonFor(m => m.AllGroups)
#Html.RadioButtonFor(m => m.AllGroups)
</div>
however if you want to do it explicitly then
you should use following syntax to check / uncheck
Html.RadioButtonFor(m => m.AllGroups, "DisplayText", new { #checked = "checked" })
In source code you can see that it is setting true / false for value not checked attribute
in your view you can write
#if(m.AllGroups)
{
Html.RadioButtonFor(m => m.AllGroups, "DisplayText", new { #checked = "checked" })
}
else
{
Html.RadioButtonFor(m => m.AllGroups, "DisplayText" })
}

Passing input value to action (ASP.Net MVC 3)

I have code in View:
#using (Html.BeginForm("MyAction", "MyController")
{
<input type="text" id="txt" />
<input type="image" src="/button_save.gif" alt="" />
}
How can I pass value of txt to my controller:
[HttpPost]
public ActionResult MyAction(string text)
{
//TODO something with text and return value...
}
Give your input a name and make sure it matches the action's parameter.
<input type="text" id="txt" name="txt" />
[HttpPost]
public ActionResult MyAction(string txt)
Add an input button inside of your form so you can submit it
<input type=submit />
In your controller you have three basic ways of getting this data
1. Get it as a parameter with the same name of your control
public ActionResult Index(string text)
{
}
OR
public ActionResult Index(FormsCollection collection)
{
//name your inputs something other than text of course : )
var value = collection["text"]
}
OR
public ActionResult Index(SomeModel model)
{
var yourTextVar = model.FormValue; //assuming your textbox was inappropriately named FormValue
}
I modified Microsoft MVC study "Movie" app by adding this code:
#*Index.cshtml*#
#using (Html.BeginForm("AddSingleMovie", "Movies"))
{
<br />
<span>please input name of the movie for quick adding: </span>
<input type="text" id="txt" name="Title" />
<input type="submit" />
}
//MoviesController.cs
[HttpPost]
public ActionResult AddSingleMovie(string Title)
{
var movie = new Movie();
movie.Title = Title;
movie.ReleaseDate = DateTime.Today;
movie.Genre = "unknown";
movie.Price = 3;
movie.Rating = "PG";
if (ModelState.IsValid)
{
db.Movies.Add(movie);
db.SaveChanges();
return RedirectToAction("Index");
}
else
{
return RedirectToAction("Index");
}
}

Resources