Checkboxes in MVC not functioning correctly - html

Ok, I posted a question on stackoverflow regarding checkboxes that had a nullable view model parameter and was told this wouldn't work. I've substantially reworked my application to support a non-nullable view model parameter so I'm ready to ask my question again.
I have a checkbox in my application, like this:
#Html.CheckBoxFor(m => m.IsNonUk)
which renders in the browser like this:
<input data-val="true" id="IsNonUk" name="IsNonUk" type="checkbox" value="true" />
<input name="IsNonUk" type="hidden" value="false" />
Inspecting the element in Chrome reveals this markup:
<input data-val="true" id="IsNonUk" name="IsNonUk" type="checkbox" value="">
<input name="IsNonUk" type="hidden" value="">
My action has this signature:
public ActionResult CreateSelfPay(CreateSelfPayViewModel viewModel)
and my CreateSelfPayViewModel view model contains this property:
public class CreateSelfPayViewModel : ViewModel
{
// ..
[DisplayName("Is non-UK")]
public bool IsNonUk { get; set; }
// ..
}
The problem is that no matter what I do to the checkbox the values posted back to the server are both null which results in a false value in the view model. I have checked this with Fiddler.
What is going on? Why can't I get a true value if the box is checked?
I hope someone can help!
== More information ==
The application is using various libraries such as jQuery, jQuery validate, jQuery UI and Bootstrap. Perhaps one of these is fiddling with the input values since they are null when inspected with the developer tools. Does anyone know of any issues in this respect?
M

Related

Using spring controller to provide list to html and make a drop down menu

I've created a controller to pass a list of pojo objects to the html. This seems to be working as when I refer to the list the IDE finds it. However, when I refer to a field within an element of the list it cannot find it and, instead of returning the value, it returns a literal text.
#GetMapping (value = "/searchforgames.html")
public String getsearchforgames(Model model) throws IOException {
List<Game> games = gamesService.getGames();
model.addAttribute("games", games);
return "searchforgames";
}
html within the searchforgames html
<div class="formformat">
<br><br>
<form>
<label for="name">Name:</label><br>
<select id="name" name="name">
<th:block th:each="game : ${games}">
<option value=${game.firstName}>${game.firstName}</option>
</th:block>
</select><br><br>
<label for="date">Date from:</label><br>
<input type="text" id="date" name="date"><br><br>
<label for="allresults">All entries</label><br>
<input type="checkbox" id="allresults" name="allresults"><br><br>
<input type="submit">
</form>
</div>
The Game class is a simple pojo with firstName, lastName, slName, sfName and date, zero argument constructor, constructor with all variables and getter/setters for each variable.
If anyone can point the error I'm doing I would be very grateful.
Use th:text to display the value for each of the options. Update value to th:value as well.
<option th:value="${game.firstName}" th:text="${game.firstName}"></option>
Using ${...} does no do much on its own, you will have to use something like th: to have thymeleaf to process the code it is referring to.

MVC5 Lost value in Textbox after Submit

I would like to clarify one thing about MVC5 Razor Views.
I was told that I don't have to use HTML Helpers (#Html.EditorFor, #Html.TextBoxFor) in my razor views and it will still work.
Controller Code
[HttpPost]
public ActionResult Create(Models.TestObj obj)
{
ViewBag.TestStr = string.Format("You typed: {0} {1}", obj.FirstName, obj.LastName);
return View(obj);
}
Razor View
#using (Html.BeginForm())
{
<div>
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control", style = "width: 120px;" } })
<input class="form-control text-box single-line" id="LastName" name="LastName" style="width: 120px;" type="text">
<input type="submit" name="submit" value="Filter" / >
</div>
#ViewBag.TestStr
}
But when I actually test it like the above, the value typed in 'LastName' textbox is not preserved. I can catch both textbox values in my Controller. But after postback, lost the value in 'LastName' textbox. The textbox which is created by using HTMLHelper didn't lose the value though.
Am I doing something wrong or is it supposed to be like that? Do I have to use HtmlHelpers in RazorViews in MVC5 if I want to keep the submitted values?
What's a "postback"? It sounds like you're trying to think of this in terms of WebForms, where the server-side controls have a lot of plumbing doing things behind the scenes.
Simply put, there is no code in your view which actually puts a value in that input. When using the HTML helpers, while the generated client-side markup is the same (and, thus, the post to the next controller action is the same), one thing that's different is that the HTML helpers will bind the control to the model that's supplied to the view.
HTML, by itself, won't do that. You can, however, do that manually:
<input value="#Model.LastName" class="form-control text-box single-line" id="LastName" name="LastName" style="width: 120px;" type="text">
^--- right here
Your not binding the second input to the value of LastName, just setting its name attribute. If you inspect the html you generating, you will note the first one has a value attribute whereas the second does not.
You need to use the EditorFor() (or TextBoxFor()) as you did for the FirstName which generates the correct value attribute (and other data-val-* attributes necessary for using client side validation).
Side note: You could also use
<input name="LastName" ..... value="#Model.LastName"` />
however this will not take into account ModelState values
You need to add the textbox in your model, and the link it in the view index.cshtml like this: m = m.Variable_name_from_your_model
Check out this site:
https://mvcstepbystep.wordpress.com/how-to-update-a-c-mvc-textbox-from-jquery/

Html.CheckBoxFor renders two inputs Which becomes an issue In Form Post

My code is like this
<div class="form-group" style="padding-top: 30px;">
#Html.CheckBoxFor(model => model.IsVatPaidByInsurer)
</div>
Inside Model Class
public bool IsVatPaidByInsurer { get; set; }
Inside Controller
public ActionResult Create([Bind(Include = "PayerID,Name,CreatedDate,PayerTypeSelected,ReferingInstitute,ApplicationUserId" +
"IsVatPaidByInsurer,PatientContribution")] Payer payer)
I expect this line of code to generate a checkbox on front end, But how it renders is like this (value not true, it's I just checked the checkbox)
<div class="form-group" style="padding-top: 30px;">
<input data-val="true" data-val-required="The IsVatPaidByInsurer field is required." id="IsVatPaidByInsurer" name="IsVatPaidByInsurer" type="checkbox" value="true">
<input name="IsVatPaidByInsurer" type="hidden" value="false">
</div>
As you can see there is two inputs with same name generated (IsVatPaidByInsurer).
And second one's value always false. So when I make my form post I can't get the real value of checkbox.It will interpret always as false there. Can anyone Tel me what This is whole about? and a way to overcome this?
The 2 inputs are correct (and without the hidden input you could get incorrect values). If the checkbox is checked, true, false is posted back and the DefaultModelBinder sets the model value to true (the second value is ignored). If the checkbox is unchecked false is posted back (unchecked checkboxes do not post back) so the model property is set to false

MVC - How to submit two sets of multiple check boxes to controller action?

I have two sets of checkboxes in a form that are both almost identical to this:
<input type="checkbox" value="1" name="Test Course"
checked="checked" />Test Course
<input type="checkbox" value="2" name="Test Course 2" />Test Course 2
<input type="checkbox" value="3" name="Test Course 3" />Test Course 3
The form is generated through Razor. Here's the code:
#using (Html.BeginForm("Save", "Material",
new { id = Model.Material.FirstOrDefault().ID },
FormMethod.Get, new { id = "associationForm" })
{
<h3>#Model.Material.FirstOrDefault().Title</h3>
Html.RenderPartial("Association/_Course", Model);
Html.RenderPartial("Association/_Track", Model);
<br />
<input type="submit" value="Save" />
}
The checkboxes are rendered through the two partial views you see in the form.
Right now, the only data being submitted successfully is new { id = Model.Material.FirstOrDefault().ID } in the 2nd line of parameters in the #using() {} statement.
I need to submit both sets of checkboxes as collections so I may iterate through them and perform some database operations. I've never done anything like this before and the only thing stopping me are these check boxes.
How can I submit those values as two separate collections?
To do this, you have to render a collection. I will assume you have two collections in your model, one called Courses, and one called Tracks.
#for(int i = 0; i < collection.Count(); i++ {
// Boolean property indicating value is selected on your Courses view model submodel
Html.CheckBoxFor(model => model.Courses[i].CourseSelected);
Html.Raw(Model.Courses[i].CourseName);
}
Then do the same for your Tracks.
EDIT;
Assuming you have a ViewModel with a List<Course> where Course looks like this:
public class Course {
public bool CourseSelected {get;set;}
public string CourseName {get;set;}
}
You will have to lookup the course based on the index of the checkbox collection. Thus, if Course[0] is set, you need to get the first course based on position. You could also look it up by name, but you will have to include a hidden field to allow it to be posted back to the form containing the name. Otherwise, you will CourseName is going to be null and you will just nave the array with the Booleans bound.
Ok, I think you need the name attribute of the inputs in the same group be the same plus square brackets like "checkgroup1[]"
<input type=checkbox name=checkgroup1[] value=1>
<input type=checkbox name=checkgroup1[] value=2>
if you define in your view two sets of check boxes, with different names, for example:
<input type=checkbox name=checkgroup1[] value="x">
.
.
.
<input type=checkbox name=checkgroup2[] value="y">
.
.
.
you can declare your post method on the controller like this:
[HttpPost]
public ActionResult YourAction(YourModel model, string[] checkgroup1, params string[] checkgroup2)
{
...
}

Multiple inputs with same name in struts

I have a form with a field that may have zero to multiple values for the named field, e.g.,:
<form ...>
<input type="hidden" name="browseId[]" value="3">
<input type="hidden" name="browseId[]" value="4">
<input type="hidden" name="browseId[]" value="8">
<input type="hidden" name="browseId[]" value="10">
<input type="text" name="browseId[]">
...
</form>
I do not seem to be able to get the variable browseId as an array, which is standard operating procedure in HTML, other languages, and I'm stumped. I'm actually first processing the form output in a validation method, using a DynaActionForm:
public static ActionMessages validatePlacement(DynaActionForm form) {
String[] rootBrowseIds = (String []) form.get("browseId");
...
}
Here's the form bean and action definition in struts-config.xml:
<form-bean name="placementForm" type="org.apache.struts.validator.DynaValidatorForm">
<!-- I've tried a few variations -->
<!--<form-property name="browseId" type="java.lang.String"/>-->
<!--<form-property name="browseIds" type="java.lang.String[]"/>-->
<form-property name="browseId" type="java.lang.String[]"/>
...
</form-bean>
...
<action path="/admin/editPlacement"
type="com.rc.mexp.action.admin.placementinventory.EditPlacementAction"
name="placementForm">
<forward name="success" path="/WEB-INF/pages/admin/placement/placementEdit.jsp"/>
<forward name="error" path="/admin/managePlacementInventory.do"/>
</action>
It appears that only the last value, empty in this case, is being received by Struts. WTF?
Any ideas?
Is there a way to change my form-bean definition to include something like this? I'm not allowed to use the < and > characters inside the type:
<form-property name="browseId" type="java.util.Map<java.lang.String[]>"/>
Other stackoverflow Qs that I examined already:
retrieve multiple inputs of the same name from jsp to struts (does not seem relevant)
Multiple inputs with same name through POST in php
Struts 2 - pattern/strategy for multiple objects on the same page
You're accessing the form field incorrectly, you should be using getStrings("browseId") since you're trying to get multiple strings.
Your code won't even compile for me, I'm not sure why you don't get a class cast exception.