Get Checkbox value in MVC Controller parameter - asp.net-mvc-5

I have a checkbox in my view that I am posting back to the Controller as a parameter, but when the checkbox is checked the controller receives the value as a string "on", and when unchecked the value in the parameter is "off". Is there any way to have this value postback as an int or bool? When I try bool below it is always null because it doesn't match the data type.
<label><input type="checkbox" name="option">food</label>
public ActionResult Select(bool? option)
{....

I guess you need to use the Html checkbox helper for this to work, which seems silly to me because it renders and works correctly client side when you create html without using the helper.
<label>#Html.CheckBox("option", false) food</label>

What you can do is add value attribute to your checkbox and set it to true or false.
MVT will not recognize option as true here
<input type="checkbox" name="option" checked="checked" />
but will if you add value="true"
<input type="checkbox" name="option" checked="checked" value="true" />
Script that does it:
$(document).on("click", "[type='checkbox']", function(e) {
if (this.checked) {
$(this).attr("value", "true");
} else {
$(this).attr("value","false");}
});

Related

XSRF token mismatch

Hi I am trying to handle a form submission via a custom controller in the admin section
This is my test controller
#Controller
#RequestMapping("/" + TempController.SECTION_KEY)
public class TempController extends AdminAbstractController {
protected static final String SECTION_KEY = "test2";
#RequestMapping(value = "", method = RequestMethod.GET)
public String test(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
// This is expected by the modules/emptyContainer template, this is a custom template that gets included into the body
model.addAttribute("customView", "views/test2");
ShippingEntity shp=new ShippingEntity();
model.addAttribute("shipping",shp);
// ensure navigation gets set up correctly
setModelAttributes(model, SECTION_KEY);
// gets the scaffolding set up to display the template from the customView attribute above
return "modules/emptyContainer";
}
#RequestMapping(value = "", method = RequestMethod.POST)
public String testPost(HttpServletRequest request, HttpServletResponse response, Model model,#ModelAttribute ShippingEntity shp) throws Exception {
// This is expected by the modules/emptyContainer template, this is a custom template that gets included into the body
model.addAttribute("customView", "views/test2");
System.out.println(shp.getLink());
System.out.println(shp.getTrackingNumber());
model.addAttribute("shipping",shp);
// ensure navigation gets set up correctly
setModelAttributes(model, SECTION_KEY);
// gets the scaffolding set up to display the template from the customView attribute above
return "modules/emptyContainer";
}
}
And this is the view template :
<div class="row">
<div class="twelve columns">
<form action="#" th:action="#{/test2}" th:object="${shipping}" method="post">
<p>Id: <input type="text" th:field="*{trackingNumber}" /></p>
<p>Message: <input type="text" th:field="*{link}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</div>
</div>
The problem is that when I submit the values I get the error:
XSRF token mismatch (null). Session may be expired
I understand that this has to do with security issues however I can't find a way to make it work.
Any tips how to solve this?
Apparently it was simpler than I thought, maybe it will help someone in the future.
Just change <form> </form> to <blc:form></blc:form>

How to call the controller from the radio button click?

How to call the controller from the radio button click ?
<div id="radio">
<input type="radio" id="Isactive" name="Isactive" value="1" />Yes</label>
<input type="radio" id="Isactive" name="Isactive" value="0" />No</label>
</div>
public ActionResult Index(CityList Obj,string Isactive)
{
return view();
}
You can use javascript to programatically submit a form. You should not have duplicate Id values for elements. Id's should be unique in a document.
#using (Html.BeginForm("Index", "Home"))
{
<!-- Your other form elements-->
<div id="radio">
<input type="radio" name="Isactive" value="Yes" />Yes
<input type="radio" name="Isactive" value="No" />No
</div>
}
Now you can listen to the change event on the radio button and use jQuery closest method to get the form and call the submit method.
$(document).ready(function () {
$("input[name='Isactive']").change(function () {
$(this).closest("form").submit();
});
});
Now when user make a selection on the radio button, the form will be submitted and the selected radio button's value attribute value will be available in your Isactive parameter of your HttpPost index action method.
If you want to pass 1 and 0, use a numeric type as the method parameter type instead of string.

How do I get checked boxes in ASP.NET MVC controller

I have a question getting checked boxes in asp.net mvc controller...
I have a form that contains many checkboxes with values.. So the user can check as many boxes he wants, and what I need is those values from the checked boxes... What I tried is getting
public ActionResult actionName(FormCollection form){...}
I do not even know how to access the checkbox value that is being passed into the function...
I have been looking for answer but could not find one.. How do I get it in the controller... I am using C# by the way.
-- edit
I have list of data and pass it into the view... Then, I create the checkbox as
<input type="checkbox" name="CheckedCart" value="#ValueForBox" />
where #ValueForBox is the value that I need to obtain in the controller if it is checked..
** I did not realize it was an old post while answering. But, it may help.
I assume you have have multiple checkboxes in the View with same name.
and you need values of the selected checkboxes in controller on form submit.
if yes, then below will help you.
in controller
[HttpPost]
public ActionResult Index(List<string> CheckedCart)
{
}
and in view
#using (Html.BeginForm())
{
<input type="checkbox" name="CheckedCart" value="value1" />
<input type="checkbox" name="CheckedCart" value="value2" />
<input type="checkbox" name="CheckedCart" value="whatever the value" />
<input type="submit" id="btnSave" value="Save" />
}
When form is submitted. You will get the values of selected checkboxes in parameter List<string> CheckedCart in index method. and values for checkboxes which are not selected will be false.
so, as per above example
if second checkbox is checked and other are false.
in the List<string> CheckedCart you will get
[0] false
[1] value2
[2] false

show and hide div click on radio button using Alloy ui

Hi I want to show and hide div using alloy ui onclick function of radio button.I mentioned my code as below.please help me to solve this problem.when i clicked on married i want to open one div it has anniversary date and when I click on single it will hide that div.
<aui:field-wrapper name="maritial_status">
<aui:input checked="<%= true %>" inlineLabel="right" name="maritial_status" type="radio" value="single" label="single" onClick="javascript:unMarriedStatus();" />
<aui:input inlineLabel="right" name="maritial_status" type="radio" value="married" label="married" onClick="javascript:marriedStatus();" />
</aui:field-wrapper>
You can solve this issue by having the function and the div class
so based on the selection call the function which will implicitly create the structure form in div method
function design:
function temp()
{
var chasisno = "";
$('#dyanamicDivElement').append(chasisno);
}
div structure:
Explanation:
so as per here the function will keep appending the value to the div
hope this solved the issue
You could try this way:
<aui:field-wrapper name="maritial_status">
<aui:input checked="<%= true %>" inlineLabel="right" name="maritial_status" type="radio" value="single" label="single" onClick="document.getElementById('DIV-ID').style.display = this.checked ? 'none' : 'block';" />
<aui:input inlineLabel="right" name="maritial_status" type="radio" value="married" label="married" onClick="document.getElementById('DIV-ID').style.display = this.checked ? 'block' : 'none';" />
</aui:field-wrapper>

Radio buttons using twitter bootstrap - unable to get value

I've browsed SO, and found some answers that have guided me closer to getting working radio buttons, but I'm stuck now.
I have the buttons, but am unable to get the value of the selected one.
I'm using JSF, hence the #{searchFlightsBean.setDir()}
Here's what I currently have:
<h:panelGrid>
<div class="btn-group" data-toggle-name="is_private" data-toggle="buttons-radio" >
<button type="button" value="0" class="btn" data-toggle="button">Public</button>
<button type="button" value="1" class="btn" data-toggle="button">Private</button>
</div>
<h:inputHidden id="hiddenDir" value="0" valueChangeListener="#{searchFlightsBean.setDir()}" onchange="submit()"/>
</h:panelGrid>
<script>
$(function() {
$('div.btn-group[data-toggle-name]').each(function() {
var group = $(this);
var form = group.parents('form').eq(0);
var name = group.attr('data-toggle-name');
var hidden = $('input[name="' + name + '"]', form);
$('button', group).each(function() {
var button = $(this);
button.on('click', function() {
hidden.val($(this).val());
});
if (button.val() == hidden.val()) {
button.addClass('active');
#{searchFlightsBean.setDir(button.value)}
}
});
});
});
</script>
In my bean, when setDir() is called, I am logging the value that it receives, like so:
public void setDir(ValueChangeEvent e) {
this.dir = e.getNewValue().toString();
log.info("NEW DIRECTION: " + this.getDir());
}
It doesn't log - setDir() is never called. For some reason the valueChangeListener attribute on the h:inputHidden tag doesn't work. Am I missing something?
Your concrete problem is caused because you used valueChangeListener the wrong way.
<h:inputHidden ... valueChangeListener="#{searchFlightsBean.setDir()}">
This does not match the method signature. You should omit the parentheses ().
<h:inputHidden ... valueChangeListener="#{searchFlightsBean.setDir}">
Otherwise JSF expects an argumentless setDir() method. Then, you're nowhere in JavaScript triggering the change event on the input element. The onchange="submit()" is therefore never invoked. You should be doing hidden.trigger("change") in JS to achieve that.
But, after all, this is somewhat clumsy. You're sending a full synchronous request and your JS code is rather overcomplicated (and stops working once you ajax-update the form). Provided that you're indeeed using JSF 2.x, I suggest to bring in <f:ajax> — which unfortunately doesn't work in <h:inputHidden>, hence the <h:inputText style="display:none"> — and to make use of $.on() in jQuery to keep the functions working even when you ajax-update the DOM.
<h:form>
<div class="btn-group" data-toggle-name="is_private" data-toggle="buttons-radio" >
<button type="button" value="0" class="btn" data-toggle="button">Public</button>
<button type="button" value="1" class="btn" data-toggle="button">Private</button>
</div>
<h:inputText id="is_private" value="#{bean.dir}" style="display: none;">
<f:ajax listener="#{bean.changeDir}" />
</h:inputText>
<!-- Note: <h:inputText id> must be exactly the same as <div data-toggle-name> -->
</h:form>
<h:outputScript>
$(document).on("click", "[data-toggle=buttons-radio] button", function() {
var $button = $(this);
var id = $button.closest(".btn-group").attr("data-toggle-name");
var $input = $button.closest("form").find("input[id$=':" + id + "']");
if ($input.val() != $button.val()) {
$input.val($button.val()).trigger("change");
}
});
</h:outputScript>
(noted should be that the whole script should really be placed in its own .js file which you include by <h:outputScript name="some.js" target="body">; note that you don't need $(document).ready() nor $(function() {}) mess; also note that the very JS function is reusable on all other <div data-toggle="buttons-radio"> groups without changes)
With this bean:
private Integer dir;
public void changeDir() {
System.out.println("New direction: " + dir);
}
// ...
(noted should be that when you're doing further nothing relevant in changeDir() method, then you could just omit the whole method and <f:ajax> altogether and revert <h:inputText style="display:none"> back to <h:inputHidden> and remove .trigger("change") and rely on the regular form submit. It'll work as good)
You cannot just call any backing bean functions via Expression Language calls (#{...}) in JavaScript.
What you could do, is using a4j:jsFunction to offer your bean method to the java script code. That might look like this:
<a4j:jsFunction name="setDir" action="#{searchFlightsBean.setDir()}" ajaxSingle="true">
<a4j:param name="dir" assignTo="#{searchFlightsBean.dir}" />
</a4j:jsFunction>
See http://docs.jboss.org/richfaces/latest_3_3_X/en/devguide/html/a4j_jsFunction.html
and http://showcase.richfaces.org/richfaces/component-sample.jsf?demo=jsFunction&skin=blueSky

Resources