In my view model I have a field. This field can be selected from a drop down list or entered in a textbox. I have two radio buttons which allows to select between drop and textbox.
<div class="frm_row" id="contractorRow">
#Html.RadioButton("IsContractorNew", "false", true)
#Html.Label(#Resources.SomeLabels.Existing)
#Html.RadioButton("IsContractorNew", "true", false)
#Html.Label(#Resources.SomeLabels.New)
<div class="frm_row_input" id="contractorDropDownList">
#Html.DropDownListFor(model => model.CONTRACTOR, Model.Contractors)
#Html.ValidationMessageFor(model => model.CONTRACTOR)
</div>
<div class="frm_row_input" id="contractorTextBox" style="display: none;">
#Html.TextBoxFor(model => model.CONTRACTOR)
#Html.ValidationMessageFor(model => model.CONTRACTOR)
</div>
</div>
I prepared a javascript code for hiding, showing and clearing controls while selecting radio buttons. The problem is - field is bound only to the first control (drop down list).
EDIT:
I solved this problem by creating one hidden field and scripting whole logic to bind active control with it and therefore with the model. Anyway if anyone knows simpler solution, please post it.
I know this is an old question, but for those dealing with this issue, here's a solution:
Explanation
When a form is submitted, input elements are bound to the model by their name attribute. Let's say you use HTML helpers to generate your form, and you generate two input fields which bind to the same property on the model. When rendered to the DOM, they both have the same name attribute.
<input name="Passport.BirthPlace" id="birthPlaceDropDown" ... >
<input name="Passport.BirthPlace" id="birthPlaceInfoTextbox" ... >
When the form is submitted, it will bind the first (in the DOM) input it finds to Passport.BirthPlace
A Solution
The quick and easy way to fix this is to use JQuery to change the name of the field you don't want bound on submit. For me, I use a checkbox to toggle which field shows. When the checkbox changes, I hide one control, change its name attribute, and show the other one (and change it's name attribute to Passport.BirthPlace) It looks like this, basically:
First, I run this on document ready
$('#birthPlaceInfoTextbox').attr('name', 'nosubmit'); // Change name to avoid binding on inactive element
Then, I create a listener for my checkbox which toggles which control should be bound:
$('#notBornUSCheckbox').change(function() {
if (this.checked) {
// Not born us was checked, hide state dropdown and show freeform text box
$('#stateDropDownSection').addClass('d-none'); // Hide drop down
$('#birthPlaceDropDown').attr('name', 'nosubmit'); // Change name to something other than Passport.BirthPlace
$('#birthPlaceInfoTextbox').attr('name', 'Passport.BirthPlace'); // Set this one to be bound to the model
$('#stateTextboxSection').removeClass('d-none'); // Show the textbox field
} else { // Opposite of above lines
$('#stateDropDownSection').removeClass('d-none');
$('#stateTextboxSection').addClass('d-none');
$('#birthPlaceInfoTextbox').attr('name', 'nosubmit');
$('#birthPlaceDropDown').attr('name', 'Passport.BirthPlace');
}
});
Instead of using Razor #Html.TextBoxFor... for your textbox, you could try using raw HTML e.g. <input />. Also, have your JavaScript code remove the other field from the DOM entirely when a radio button is clicked, before submitting the form.
Related
I have a web document that has its fields populated dynamically from c# (.aspx.cs).
Many of these fields are TextBox or HtmlTextArea elements, but some are Checkbox elements.
For each of these I have the ID attribute populated on creation of the field, as well as using .Attributes.Add("onchange","markChanged(this.id)")
This works great on all the fields except Checkbox. So I created a markCheckChange as I discovered that the Checkbox won't accept style="backgroundColor:red" or .style.backgroundColor = "red" type arguments.
I also added an alert and found that the Checkbox is not actually passing the this.id into the parameter for markCheckChange(param) function.
As a result I am getting errors of the type:
unable to set property of undefined or null reference
Why and what is the difference between these controls, and is there a better way to handle this?
I just reviewed the inspect element again, and discovered that the Checkbox control is creating more than an input field of the type checkbox, it is also wrapping it in a span tag, and the onchange function is being applied to the span tag (which has no id) and not to the input tag that has the checkbox id. Whereas for TextBox and HtmlTextArea the input tag is put directly within the cell/td tag, no some arbitrary span tag.
So now the question becomes how to get the onchange function to apply to the input tag for the checkbox rather than the span tag encapsulating it?
Per request:
function markChange(param) {
if (userStatus == "readonly") {
document.getElementById("PrintRecButton").style.display = "none";
document.getElementById("PrintPDFButton").style.display = "none";
alert("Please login to make changes.\n\nIf you do not have access and need it,\n contact the administrator");
exit();
}
else {
document.getElementById(param).style.backgroundColor = "teal";
saved = false;
var page = document.getElementById("varCurrentPage").value;
markSaveStatus(page, false);
}
}
So far the markCheckChange is about the same, until I get it to pass the id correctly, I won't be able to figure out the right way to highlight the changed checkboxes.
I found an alternative.
As I mentioned in the edit to the question, the inspect element feature revealed that the CheckBox type control was creating a set of nested elements as follows:
<span onchange="markChange(this.id)">
<input type="checkbox" id="<someValue>">
<label for="<someValue>">
</span>
Thus when the onchange event occurred it happened at the span which has no id and thus no id was benig passed for the document.getElementById() to work.
While searching for why I discovered:
From there I found the following for applying labels to the checkboxes:
https://stackoverflow.com/a/28675013/11035837
So instead of using CheckBox I shall use HtmlInputCheckBox. And I have confirmed that this correctly passes the element ID to the JavaScript function.
I have an ASP.NET MVC application. I am having multiple drop-down list in my page (HTML SELECT), I have to disable them, as user goes on selected them one by one. When the user posts it back to the controller, I am getting null as the function (action method) paramters. I searched and found that HTML does not send value of disabled fields in the form data. Replacing disabled attribute with readonly would not work as it would render drop-down working.
I am generating the dropdowns dynamically using javascript as user goes on. So there isn't a single dropdown, but as many as user wants.
Can someone please tell me how should I get the values ?
One possibility is to make the dropdown list disabled="disabled" and include a hidden field with the same name and value which will allow to send this value to the server:
#Html.DropDownListFor(x => x.FooId, Model.Foos, new { disabled = "disabled" })
#Html.HiddenFor(x => x.FooId)
If you have to disabled the dropdown dynamically with javascript then simply assign the currently selected value of the dropdown to the hidden field just after disabling it.
This is the default behavior of disabled controls. I suggest you to add a hidden field and set the value of your DropDownList in this hidden field and work with this.
Something like:
//just to create a interface for the user
#Html.DropDownList("categoryDump", (SeectList)ViewBag.Categories, new { disabled = "disabled" });
// it will be send to the post action
#Html.HiddenFor(x => x.CategoryID)
You could also create your own DropDownListFor overload which accepts a bool disabled parameter and does the heavy lifting for you so your view isn't cluttered with if disablethisfield then ....
Something among these lines could do:
public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, bool disabled)
{
if (disabled)
return MvcHtmlString.Create(htmlHelper.HiddenFor(expression).ToString() + htmlHelper.DropDownListFor(expression, selectList, new { disabled="disabled" }).ToString());
else
return htmlHelper.DropDownListFor(expression, selectList);
}
There are 6 overloads for DropDownListFor alone so it's a lot of monkeycoding but it pays off in the end imho.
Create a hidden field with a specified Id and set it before disabling the drop-down-list.
In MVC,
#Html.DropDownListFor(x => x.FooId, Model.Foos)
#Html.HiddenFor(x => x.FooId, new { #id = "hdnFooId" })
In JQuery,
function handleDropDownListFooChange(){
// Get the selected value from drop-down-list before disabling it.
var selectedFooId = $('#FooId').val();
$('#FooId').prop("disabled", "disabled");
$("#hdnFooId").val(selectedFooId);
// Load any data the depends on selected FooId using `selectedFooId` variable.
}
The selected value will automatically be binded to Model.FooId.
before submit call $('#FooId').removeAttr('disabled')
In this AngularJS controller for a pre-filled form, fetching the data is triggered by an event using $broadcast and $on. However, when the data updates, only some of the corresponding fields get updated in the view.
$scope.currentHouse = {};
$scope.$on('houseInfoLoad', function(event, data) {
$scope.currentHouse = data.houseDetail; //does not refresh the view
console.log($scope.currentHouse); //output is correct
//the next three calls refresh the corresponding fields in the view
$scope.changeGarageRadioValue($scope.currentHouse.hasGarage);
utils.setSelection($scope.houseKeywords, $scope.currentHouse.keyword.id);
utils.setSelection($scope.houseTypes, $scope.currentHouse.type.id);
});
changeGarageRadioValue() essentially does what it says, and utils.setSelection(list, id) adds a selected = true property to the element of the list that has the id. This has the effect of setting the value of a select field (using isteven's multi-select plugin).
The view has a few text fields bound to properties of $scope.currentHouse, as well as these radio buttons and select fields.
The result is that the text fields sometimes do not get updated, however the select and radio buttons do.
Here's what I tried unsuccessfully:
Wrapping everything in a $timeout();
Calling $scope.$apply() after setting $scope.currentHouse (throws an error saying that we are already inside an $apply())
Changing the initial definition of $scope.currentHouse from {} to an object with each of the fields set to null.
Can anyone see what I am missing, or how to force trigger the refresh?
EDIT : with extracts from the view :
A text field:
<label>ADDITIONAL DESCRIPTION</label>
<div>
<input type="text" ng-model="currentHouse.additionalDescription" class="input-mandatory" value=""/>
</div>
A multi-select:
<label>TYPE</label>
<div>
<div directive-id="houseType" multi-select input-model="houseTypes" output-model="currentHouse.type" button-label="text" item-label="text" selection-mode="single" default-label="Select" tick-property="selected" ></div>
</div>
The radio buttons :
<div><label>HAS GARAGE</label></div>
<div>
<div id="radiobuttonNo" ng-click="changeGarageRadioValue(false);">
NO
</div>
<div id="radiobuttonYes" ng-click="changeGarageRadioValue(true);" class="active">
YES
</div>
</div>
EDIT #2 as per Alok Singh's suggestion:
I tried putting data.houseDetail into $scope.currentHouse.house instead of $scope.currentHouse directly, and changing the view accordingly. Still no results.
$scope.currentHouse = data.houseDetail
You cannot get the updated value of currentHouse because its a model.
So change the above code i.e
$scope.currentHouse.house = data.houseDetail
I have a form where the user can select a generic auto-population based on checking a radio button. When the user checks the auto-populate radio button, the fields are auto populated with the data and then the fields become disabled.
In this first part of the function, I pass the auto-filled data:
$('#myOptions').click(function()
$('#value1').val("Auto-filled data");
$('#Value2').val("Auto-filled data");
$('#Value3').val("Auto-filled data");
In this second part, I am disabling the html inputs
// now i am disabling the html inputs:
$('#Value4').prop("disabled", true);
$('#Value5').prop("disabled", true);
$('#value6').prop("disabled", true);
Suppose I have another field with an ID of "Value7" in the form, that I would like to hide from the user interface as part of this function.
How can I hide the "Value7" input upon function triggering? I appreciate the help, I am very new to JavaScript, though I find it very exciting!
Using jquery:
To hide
jQuery('#Value7').hide() or jQuery('#Value7').css("display","none")
To show the element back
jQuery('#Value7').show() or jQuery('#Value7').css("display","block")
or pure js:
javascript hide/show element
Try this javascript:
if you want disable:
document.getElementById('#Value7').setAttribute("disabled","disabled");
if you want enable:
document.getElementById('#Value7').removeAttribute('disabled');
if you want to hide :
document.getElementById('#Value7').css("display","none");
if you want to show:
document.getElementById('#Value7').css("display","block");
I am not getting what are you trying to ask actualy .
Let me know if this helps -
$("Value7").hide()
I have a page with lots of forms on it and every form has a dropdown and two buttons - ok and decline. I have an onclick that will trigger a function:
<input type="button" value="decline"
class="submit_button_wow"
onclick="submit_decision({{ x.id }},false,this)">
how do I figure the selected dropdown value from this form inside submit_decision?
{{x.id}}
is the id of decision that I fill out via template engine.
You're passing a reference to button to the submit_decision (the this). From it you can get parent form and, subsequently, the dropdown and its value.
Try something like this:
$(sender).parent("form").find("select").first().val()
Refrence the form from the button's form property. Then get the drop down list by its name.
function submit_decision(decision, myBool, button) {
var dropdown = button.form.myDropdown;
var selectedValue = $(dropdown).val();
}