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"/>
Related
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.
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.
Here the controller view file SuiteCRM/modules/Contacts/views/view.detail.php
<?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
require_once('include/MVC/View/views/view.detail.php');
require_once('api/soap_api.php');
class ContactsViewDetail extends ViewDetail
{
/**
* #see SugarView::display()
*
* We are overridding the display method to manipulate the portal information.
* If portal is not enabled then don't show the portal fields.
*/
public function display(){
global $sugar_config;
$aop_portal_enabled = !empty($sugar_config['aop']['enable_portal']) && !empty($sugar_config['aop']['enable_aop']);
//echo '<pre>===='; print_r($aop_portal_enabled); exit;
$this->ss->assign("AOP_PORTAL_ENABLED", $aop_portal_enabled);
require_once('modules/AOS_PDF_Templates/formLetter.php');
formLetter::DVPopupHtml('Contacts');
$admin = new Administration();
$obj = new AirtelUserInfo();
$res = $obj->test();
$sql = 'select * from contacts';
//$result = $this->db->query($sql,true," Error filling in additional detail fields: ");
// Get the id and the name.
//$row = $this->db->fetchByAssoc($result);
//echo '<pre>'; print_r($sql); exit;
$this->ss->assign("res", $res);
$admin->retrieveSettings();
if(isset($admin->settings['portal_on']) && $admin->settings['portal_on']) {
$this->ss->assign("PORTAL_ENABLED", true);
}
parent::display();
}
}
here the tpl file path
SuiteCRM/cache/modules/Contacts/DetailView.tpl
<script language="javascript">
{literal}
SUGAR.util.doWhen(function(){
return $("#contentTable").length == 0;
}, SUGAR.themes.actionMenu);
{/literal}
</script>
<table cellpadding="0" cellspacing="0" border="0" width="100%" id="">
<tr>
<td class="buttons" align="left" NOWRAP width="80%">
<div class="actionsContainer">
<form action="index.php" method="post" name="DetailView" id="formDetailView">
<input type="hidden" name="module" value="{$module}">
<input type="hidden" name="record" value="{$fields.id.value}">
<input type="hidden" name="return_action">
<input type="hidden" name="return_module">
<input type="hidden" name="return_id">
<input type="hidden" name="module_tab">
<input type="hidden" name="isDuplicate" value="false">
<input type="hidden" name="offset" value="{$offset}">
<input type="hidden" name="action" value="EditView">
<input type="hidden" name="sugar_body_only">
</form>
<ul id="detail_header_action_menu" class="clickMenu fancymenu" ><li class="sugar_action_button" >{if $bean->aclAccess("edit")}<input title="{$APP.LBL_EDIT_BUTTON_TITLE}" accessKey="{$APP.LBL_EDIT_BUTTON_KEY}" class="button primary" onclick="var _form = document.getElementById('formDetailView'); _form.return_module.value='Contacts'; _form.return_action.value='DetailView'; _form.return_id.value='{$id}'; _form.action.value='EditView';SUGAR.ajaxUI.submitForm(_form);" type="button" name="Edit" id="edit_button" value="{$APP.LBL_EDIT_BUTTON_LABEL}">{/if} <ul id class="subnav" ><li>{if $bean->aclAccess("edit")}<input title="{$APP.LBL_DUPLICATE_BUTTON_TITLE}" accessKey="{$APP.LBL_DUPLICATE_BUTTON_KEY}" class="button" onclick="var _form = document.getElementById('formDetailView'); _form.return_module.value='Contacts'; _form.return_action.value='DetailView'; _form.isDuplicate.value=true; _form.action.value='EditView'; _form.return_id.value='{$id}';SUGAR.ajaxUI.submitForm(_form);" type="button" name="Duplicate" value="{$APP.LBL_DUPLICATE_BUTTON_LABEL}" id="duplicate_button">{/if} </li><li>{if $bean->aclAccess("delete")}<input title="{$APP.LBL_DELETE_BUTTON_TITLE}" accessKey="{$APP.LBL_DELETE_BUTTON_KEY}" class="button" onclick="var _form = document.getElementById('formDetailView'); _form.return_module.value='Contacts'; _form.return_action.value='ListView'; _form.action.value='Delete'; if(confirm('{$APP.NTC_DELETE_CONFIRMATION}')) SUGAR.ajaxUI.submitForm(_form);" type="submit" name="Delete" value="{$APP.LBL_DELETE_BUTTON_LABEL}" id="delete_button">{/if} </li><li>{if $bean->aclAccess("edit") && $bean->aclAccess("delete")}<input title="{$APP.LBL_DUP_MERGE}" class="button" onclick="var _form = document.getElementById('formDetailView'); _form.return_module.value='Contacts'; _form.return_action.value='DetailView'; _form.return_id.value='{$id}'; _form.action.value='Step1'; _form.module.value='MergeRecords';SUGAR.ajaxUI.submitForm(_form);" type="button" name="Merge" value="{$APP.LBL_DUP_MERGE}" id="merge_duplicate_button">{/if} </li><li><input class="button" id="manage_subscriptions_button" title="{$APP.LBL_MANAGE_SUBSCRIPTIONS}" onclick="var _form = document.getElementById('formDetailView');_form.return_module.value='Contacts'; _form.return_action.value='DetailView'; _form.return_id.value='{$fields.id.value}'; _form.action.value='Subscriptions'; _form.module.value='Campaigns'; _form.module_tab.value='Contacts';_form.submit();" name="Manage Subscriptions" type="button" value="{$APP.LBL_MANAGE_SUBSCRIPTIONS}"/></li><li><input type="button" class="button" onClick="showPopup();" value="{$APP.LBL_GENERATE_LETTER}"/></li><li>{if !$fields.joomla_account_id.value && $AOP_PORTAL_ENABLED}<input title="{$MOD.LBL_CREATE_PORTAL_USER}" class="button" onclick="var _form = document.getElementById('formDetailView');_form.action.value='createPortalUser';_form.submit();" name="buttonCreatePortalUser" id="createPortalUser_button" type="button" value="{$MOD.LBL_CREATE_PORTAL_USER}"/>{/if}</li><li>{if $fields.joomla_account_id.value && !$fields.portal_account_disabled.value && $AOP_PORTAL_ENABLED}<input title="{$MOD.LBL_DISABLE_PORTAL_USER}" class="button" onclick="var _form = document.getElementById('formDetailView');_form.action.value='disablePortalUser';_form.submit();" name="buttonDisablePortalUser" id="disablePortalUser_button" type="button" value="{$MOD.LBL_DISABLE_PORTAL_USER}"/>{/if}</li><li>{if $fields.joomla_account_id.value && $fields.portal_account_disabled.value && $AOP_PORTAL_ENABLED}<input title="{$MOD.LBL_ENABLE_PORTAL_USER}" class="button" onclick="var _form = document.getElementById('formDetailView');_form.action.value='enablePortalUser';_form.submit();" name="buttonENablePortalUser" id="enablePortalUser_button" type="button" value="{$MOD.LBL_ENABLE_PORTAL_USER}"/>{/if}</li><li>{if $bean->aclAccess("detail")}{if !empty($fields.id.value) && $isAuditEnabled}<input id="btn_view_change_log" title="{$APP.LNK_VIEW_CHANGE_LOG}" class="button" onclick='open_popup("Audit", "600", "400", "&record={$fields.id.value}&module_name=Contacts", true, false, {ldelim} "call_back_function":"set_return","form_name":"EditView","field_to_name_array":[] {rdelim} ); return false;' type="button" value="{$APP.LNK_VIEW_CHANGE_LOG}">{/if}{/if}</li></ul></li></ul>
</div>
</td>
In your view you will need to assign your variable in the display method like following:
$myArray = array(1000, 1001, 1002);
$this->ss->assign("myArray", $myArray);
Then you will need to edit the smarty template:
<ul>
{foreach from=$myArray item=foo}
<li>{$foo}</li>
{/foreach}
</ul>
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);
public ActionResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = Convert.ToInt16(Request.Form["Customerid"]);
objCustomer.CustomerCode = Request.Form["code"];
objCustomer.Amount = Convert.ToDouble(Request.Form["amount"]);
return View(objCustomer);
}
This is my action in controller(MVC 2 aspx):
<form action="DisplayCustomer" method="post">
Customer id:-
<input type="text" id="Customerid" /><br />
Customer Code:-
<input type="text" id="code" /><br />
Customer amount:-
<input type="text" id="amount" /><br />
<input type="submit" value="click here" />
</form>
This is the view. When someone hit the submit button it is directed to a new page:
<div>
<b> ID</b> <%= Model.Id %><br />
<b> Code </b><%=Model.CustomerCode %><br />
<b> Amount</b> <%=Model.Amount %><br />
</div>
I always get 0 in Id and Amount while blank in CustomerCode.
Any clue? Why this is happening? What is wrong?
Your issue here is that you set the id, and not the name. Set the name to get the post back value. Eg:
<input type="text" name="Customerid" />
read also: HTML input - name vs. id in the line "Used on form elements to submit information"