springmvc how to send multi dimensional radiobutton array to controller - spring-mvc

I am trying to make a feedback from but i am not able to get any example on how to send multidimensional int array from form to controller.
feedback from pic : http://oi58.tinypic.com/p1z10.jpg
Controller
#RequestMapping(value = "/submitfeedback", method = RequestMethod.POST)
public String postsubmitfeedback(#ModelAttribute("answer") #RequestParam("email") String email,
#RequestParam("feedback_id") Integer feedback_id, #RequestParam(value="myanswer[]") int [] myanswer, Answer answer,
Locale locale) {
for(int i=0; i<myanswer.length;i++) {
System.out.println(myanswer[i]);
}
return "submitfeedback";
}
Jsp Form
<form:form commandName="feedback">
<c:forEach items="${questionList}" var="question">
<c:set var="counter" value="${counter + 1}"/>
<tr>
<td>${counter}</td>
<td>${question.question}</td>
<td><input type="radio" name="myanswer[${count}]" id="radio" value="1" /> 1</td>
<td><input type="radio" name="myanswer[${count}]" id="radio" value="2" /> 2</td>
<td><input type="radio" name="myanswer[${count}]" id="radio" value="3" /> 3</td>
<td><input type="radio" name="myanswer[${count}]" id="radio" value="4" /> 4</td>
<td><input type="radio" name="myanswer[${count}]" id="radio" value="5" /> 5</td>
</tr>
<c:set var="count" value="${count+1}"/>
</c:forEach>
</form:form>

First, I strongly recommend you to encapsulate your parameters in an object.
class FeedbackForm {
private String email;
private Integer feedbackId;
private Integer answer;
/** Getters and setters. */
}
The html form inputs' names should match the field names.
Secondly, you have a radio button control, I doubt you will end up with an array of ints, since you can only have one radio button selected at all times. In the bean above, I've corrected it to a single answer. Radio buttons are a bit bizarre, since they're multiple inputs inside the form. you should probably have something like this :
<input type="radio" name="answer" value="1" onClick="changeMyHiddenField()" />1
<input type="radio" name="answer" value="2" onClick="changeMyHiddenField()" />2
<input type="radio" name="answer" value="3" onClick="changeMyHiddenField()" />3
<form {...}> <input id="myHiddenField" type="hidden" name="answer" /> </form>
Thirdly, You have no validation of the client's input. You should take advantage of Spring's bean validation.
#Min(value = 1, message = "Min is 1.")
#Max(value = 5, message = "Max is 5.")
private Integer answer;
Finally, your method signature should look like this:
public String postFeedback(#ModelAttribute #Valid FeedbackForm form, HttpServletRequest request, Locale locale);

Related

How to bind form data using spring #ModelAttribute in a model which contains reference of different object

Hi I have a form which have many input tags with address input tag like below
input tag for : name
input tag for :password
input tage for : stree
input tage for : city
input tage for : state
The problem is with model where i have Address class inside user class like below
private String name;
private String password;
private Address address;
How to pass values of address inside Address class using spring #ModelAttribute annotation
Assuming the name of the class you provided is "Person" ( Person has an Address).
hence 2 classes Person class and an Address Class. Make sure the getters and setters are
set for the variables and object references.
<form:form method="post" action="" modelAttribute="Person">
<form:input type="text" placeholder="" path="name" />
<form:input type="password" placeholder="" path="password" />
<form:input type="text" placeholder="" path="address.street" />
<form:input type="text" placeholder="" path="address.city" />
<form:input type="text" placeholder="" path="address.state" />
</form:form>

Why does my onClick() button call the HttpPost method within my controller?

I have a button which onClick() execute a JS script, but for some reason it keeps executing my SubmitForm() Action method within my controller and i don't understand why
#using (Html.BeginForm("SubmitForm", "Home", FormMethod.Post,
new
{
traName = Request.Form["nameOfTra"],
amount = Request.Form["amountRequested"],
memberName = Request.Form["commiteeMember"],
date = Request.Form["agmDate"],
signed = Request.Form["signed"],
dated = Request.Form["dated"],
numberOfRows = Request.Form["numberOfRows"]
}))
{
<h1 style="text-align: center;"> TRA grant application </h1>
<h4 style="text-align: center;">This is the TRA Grant form for the association named below who agree to use these funds to cover the cost of administration of the TRA</h4>
<p>
<label for="nameOfTralbl">Name of TRA:</label>
<input type="text" name="nameOfTra" value="" />
</p>
<h4> List of items the money will be spent on</h4>
<table id="traTable">
<tr>
<td>Description of Items</td>
<td>Quantity</td>
<td>Cost</td>
</tr>
<tr>
<td><input type='text' size="30" /></td>
<td><input type='text' size="30" /></td>
<td><input type='text' size="30" /></td>
</tr>
</table>
<br />
<button onclick="addRow()">Add Item</button>
<input type="hidden" id="rows" value="1" name="numberOfRows" />
<script>
function addRow() {
var table = document.getElementById("traTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "<input type='text' size='30' id='cell1_" + $('#rows').val() + "'/>";
cell2.innerHTML = "<input type='text' size='30' id='cell2_" + $('#rows').val() + "'/>";
cell3.innerHTML = "<input type='text' size='30' id='cell3_" + $('#rows').val() + "'/>";
$('#rows').val(parseInt($('#rows').val()) + 1)
}
</script>
public ActionResult SubmitForm(string traName, float? amount,
string memberName, string date, string signed, string dated, int? numberOfRows, HttpPostedFileBase file, HttpPostedFileBase file2, HttpPostedFileBase file3){}
I have some extra logic in my Submitform() action which I dont want to execute, I dont understand why it keeps calling this action which it should simply just call the script.
You not declared your submit button to your SubmitForm(). Add inside FormBegin your submit button:
<input type="submit" value="Submit Button" />
#Edit:
Change:
<button onclick="addRow()">Add Item</button>
To:
<input type="button" onclick="addRow()" value="Add Item"/>

How to pass model list to controller [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 4 years ago.
I am trying to post a list of objects from View to controller.
Below is my code:
View :
#using Models
#model IList<Add>
#{
ViewData["Title"] = "AddNewFields";
}
<form asp-controller="Trans" asp-action="InsertFields" method="post" class="form-horizontal card-body" role="form">
<td><input type="text" class="form-control" value="Field Size" asp-for="#Model[i].TypeFlag"/></td>
<td><input type="text" class="form-control" value="Field Value" asp-for="#Model[i].FieldValue"/></td>
<td><input type="text" class="form-control" value="Field Format" asp-for="#Model[i].FieldFormat"/></td>
</form>
I will be adding mo these text fields again on button click.
Model:
public class Add
{
public string TypeFlag { get; set; }
public string FieldValue { get; set; }
public string FieldFormat { get; set; }
}
Controller:
public string InsertFields(IList<Add> fields)
{
//some logic
}
When I run the application, I am getting the below error:
NullReferenceException: Object reference not set to an instance of an object.
AspNetCore.Views_Trans_Add.<ExecuteAsync>b__27_0() in AddNewFields.cshtml
#for (int i = 0; i < Model.Count; i++)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext.GetChildContentAsync(bool useCachedResult, HtmlEncoder encoder)
Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output)
Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.RunAsync(TagHelperExecutionContext executionContext)
Please help me...I am stuck here from 2 days..
2 issues:
Model is null
Action will not get values.
solution:
Your HTML should be this style
#{
var fields = (Model ?? Enumerable.Empty<Add>()).ToList(); //this variable must be same with the parameter in action.
}
<form asp-action="Test" method="post">
<table class="table">
<tbody>
<tr>
<td>
<div class="form-group">
<input type="submit" value="Submit" />
</div>
</td>
</tr>
#for (var i = 0; i < fields.Count; i++) //you must use for, not foreach
{
<tr>
<td>
<div class="form-group">
<input type="hidden" asp-for="#fields[i].Id" />
<input asp-for="#fields[i].Name" class="form-control" />
</div>
</td>
</tr>
}
</tbody>
</table>
</form>
your controller should be this:
[HttpPost]
public async Task<IActionResult> Test(IEnumerable<Add> fields)
//be aware: the parameter name "fields" must be same with your html
//the type should be "IEnumerable<Add>", more compatible with different versions of MVC
{
.....your logic
return Json(new { ... });
}
the generated html is this style:
<tr>
<td>
<div class="form-group">
<input type="hidden" id="fields_0__Id" name="fields[0].Id" value="14">
<input class="form-control" type="text" id="fields_0__Name" name="fields[0].Name" value="xxxxx">
</div>
</td>
</tr>
<tr>
<td>
<div class="form-group">
<input type="hidden" id="fields_1__Id" name="fields[1].Id" value="1">
<input class="form-control" type="text" id="fields_1__Name" name="fields[1].Name" value="xxxx">
</div>
</td>
</tr>
you will see the reason: the parameter fields is just a field of html form, they must match each other.

ASP.net MVC Razor - binding checkboxs to bool values

I can't figure out how to get selected checkboxes to become "true" and unselected checkboxes to become "false" bool values. Here is a sample of the code I am working on.
Note: My put function is getting a 200 response but the checkboxes just are not updating the bool.
Model
public class AccountFeatures
{ public bool? FormCopy { get; set; }
public bool? FormRename { get; set; }
public bool? FormTransfer { get; set; }
public bool? FormDelete { get; set; }
public bool? FormEdit { get; set; }
public bool? FormComplete { get; set; }
}
View
`$('.ui.form.accountfeatures').form({
on: 'blur',
inline: true,
onSuccess: function () {
$('#features').dimmer('show');
$.ajax({
method: 'PUT',
data: { FormRename: $("#FormRename").val() ? true : false,
FormTransfer: $("#FormTransfer").val() ? true : false,
FormDelete: $("#FormDelete").val() ? true : false,
FormEdit: $("#FormEdit").val() ? true : false,
FormComplete: $("#FormComplete").val() ? true : false}
HTML
<tr>
<td>Form Copy</td>
<td class="center aligned">
<input type="checkbox" name="FormCopy" id="FormCopy" value="False" checked="#Model.Account.Features.FormCopy">
</td>
</tr>
<tr>
<td>Form Rename</td>
<td class="center aligned">
<input type="checkbox" name="FormRename" id="FormRename" value="FormRename" checked="#Model.Account.Features.FormRename">
</td>
</tr>
<tr>
<td>Form Transfer</td>
<td class="center aligned">
<input type="checkbox" name="FormTransfer" id="FormTransfer" value="FormTransfer" checked="#Model.Account.Features.FormTransfer">
</td>
</tr>
<tr>
<td>Form Delete</td>
<td class="center aligned">
<input type="checkbox" name="FormDelete" id="FormDelete" value="FormDelete" checked="#Model.Account.Features.FormDelete">
</td>
</tr>
<tr>
<td>Form Edit</td>
<td class="center aligned">
<input type="checkbox" name="FormEdit" id="FormEdit" value="FormEdit" checked="#Model.Account.Features.FormEdit">
</td>
</tr>
<tr>
<td>Form Complete</td>
<td class="center aligned">
<input type="checkbox" name="FormComplete" id="FormComplete" value="FormComplete" checked="#Model.Account.Features.FormComplete">
</td>
</tr>
I typically use an EditorFor and it just works:
#Html.EditorFor(m => m.CheckBoxProperty)
However, I also typically only use bool, not bool? for my checkbox properties.
Something to note regarding the checked attribute - you usually either use just the attribute name, as in:
<input type="checkbox" name="FormComplete" id="FormComplete" value="FormComplete" checked />
Or you use checked="checked", as in:
<input type="checkbox" name="FormComplete" id="FormComplete" value="FormComplete" checked="checked" />
Any other way, like putting checked="true" or checked="false" doesn't produce the outcome that you would expect, or at the very least, is not consistent amongst all browsers. What these use cases usually result in are checked boxes, regardless of whether you wanted that, or not. Here's a quick mock up to demonstrate:
<input type="checkbox" value="test" name="test1" /> Test 1<br />
<input type="checkbox" value="test" name="test2" checked /> Test 2<br />
<input type="checkbox" value="test" name="test3" checked="checked" /> Test 3<br />
<input type="checkbox" value="test" name="test4" checked="true" /> Test 4<br />
<input type="checkbox" value="test" name="test5" checked="false" /> Test 5
And a screenshot of the output under Chrome 57:
Essentially, you want to use logic to determine whether to insert the checked attribute altogether, rather than inserting it and having the logic set it to true or false.

Help required with a radio button based MVC User Control

I have an MVC user control that displays radio buttons in my MVC app. The issue is that how do I get it to display unique q group name for each control. I need to somehow pass it a parameter to that the name is not set as the same as every other group of radio buttons that I have used the control for on the page.
If this were not MVC I would know how to do this straight away.
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<td><input type="radio" name="need" value="4"/></td>
<td><input type="radio" name="need" value="3"/></td>
<td><input type="radio" name="need" value="2"/></td>
<td><input type="radio" name="need" value="1"/></td>
<td><input type="radio" name="current" value="4"/></td>
<td><input type="radio" name="current" value="3"/></td>
<td><input type="radio" name="current" value="2"/></td>
<td><input type="radio" name="current" value="1"/></td>
Thanks
Andy
If you pass some model data to the user control, then you will be able to use this to group your radio buttons.
Change the top line to declare the model type you are passing, such as:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Group>" %>
Where the class 'Group' is a class of your making containing the group's name.
e.g.
public class Group
{
public string Name { get; set; };
}
Then have your user control render the following:
<td><input type="radio" name="<%: Model.Name %>" value="4"/></td>
<td><input type="radio" name="<%: Model.Name %>" value="3"/></td>
<td><input type="radio" name="<%: Model.Name %>" value="2"/></td>
<td><input type="radio" name="<%: Model.Name %>" value="1"/></td>
You can then show this user control using the RenderPartial HTML helper from it's parent multiple times based on the group name that you require.
<% Html.RenderPartial("PartialControlName", new Group { Name = "need" }); %>

Resources