Multiple controls in MVC view that modify same model value - asp.net-mvc

I have a field in my model - call it 'distance' - and I want to write a view that contains both a checkbox and a textbox.
If the checkbox is checked, the textbox becomes disabled and 'distance' gets the value 0 when the form is submitted.
If the checkbox is not checked, 'distance' gets whatever value is in the textbox when the form is submitted.
Anybody have any guidance how to do this? It's the logic of assigning a model value based on the state of both the controls that confusing me...

The UI behaviour can be accomplished with Javascript via an onclick event handler on the checkbox. The only value you need to submit is the input field whose value will be set to 0 or whatever is set manually.
With jQuery you would have:
$('#checkbox_id').click(function() { $('inputfield_id').val('0');

The Model behavior depends on what the checkbox represents. If it's an actual property on the Model, then you will need to check the value server-side as well as (optionally) using aleemb's javascript method.
If a check in that field simply represents a distance of zero, then aleemb's method will suffice.

Aleemb's answer worked like a charm, with a couple of minor modifications:
$("#Distance_checkbox").click(function() {
if ($(this).is(':checked')) {
$("#Distance_textbox").val(0);
$("#Distance_textbox").attr("disabled", true);
}
else {
$("#Distance_textbox").val("");
$("#Distance_textbox").attr("disabled", false);
}
});

Related

Adding fields to form based on a value in MVC 5

I have a drop down in my view. Say the selected value is 1, I want to show the next field as textbox.
#f.FormGroup().TextBoxFor(model => model.Parameter)
If the selected value is 2, then i need it as a dropdown with a list of values.
#f.FormGroup().DropDownListFor(model => model.Parameter, Model.ForumList)
If the selected value is 3, then i need to hide the parameter.
What is the best way to acheive this?
Thanks in advance,
Vanitha.
Add a function inside javascript that should be called onChange event of your dropdownlist. Pass the value of dropdown to that on change function and use if condition to decide which element to show, for this purpose you can keep a div and append elements inside it on runtime
function myfunc(dropValue)
{
if(dropValue==1)
document.getElementbyId('yourdiv').innerHtml=//the html for your element in ''
}

Select from drop down menu or add another

I'm using simple_form. How can I have a select menu and a text input and have something like Select or add another.
The app will only take one value, either from the select menu or the text input.
It would also be good to validate to have either one or the other but not both, to avoid user confusion.
Implement what is called a 'combobox' to your simple_form
Jquery UI has a combobox:
http://jqueryui.com/autocomplete/#combobox
something fancier:
http://demos.kendoui.com/web/combobox/index.html
This will get you as far as your combo boxes displaying. I don't think there is a plugin for validating, so you'll have to write the code yourself.
You can try to use a combination of JavaScript and Ruby to solve this. If a user wants to enter a different value then what's available in the dropdown, you should have JS listen to a keydown event in that input and clear the dropdown, i.e.:
$(".input_field").bind('keydown', function() {
$(".select_field").val('0') // this should be a default blank value
});
That will clear the select when a user types. Likewise, you want to clear the input when the user selects from the dropdown, right?
$(".select_field").change(function() {
// Let's only clear the input field if the value is not the default null value
if ( $(this).val() != 0 ) {
$(".input_field").val('');
}
});
This will handle the front-end interactions. In the controller, you'll want to do some additional logic:
def create
object.new(...)
if params[:select] and params[:input]
# Overwrite the select with the input value
object.attribute = params[:input]
end
object.save
end
I assume that you want the input value to supersede the select, therefore if they are most submitted, we can just overwrite the select value with the input value and then continue to save the object.
Is this what you're looking for? Not sure if the inputted value was suppose to create a new object with a relationship or not. Hope this helps.

asp.net mvc disabled text box updated by javascript does not post new value

I am using a strongly typed model for my view. I have a disabled text box whose value I update using javascript. The textbox is rendered using this
<%: Html.TextBoxFor(model => model.TotalAmount, new { disabled = "disabled"})%>
This renders a textbox with NAME and ID as 'TotalAmount'. TotalAmount is also a property on my model that binds to this view.
The javascript to update its value in the view is like this within its function:
document.getElementById('TotalAmount').value = {assigning new value here};
The function does get called and I can see the value in the disabled textbox when I change some value in another editable textbox. However, when I post this form to my action method as below :
[HttpPost]
public ActionResult Process (ProcessVM FormPostVM)
{
}
the disabled textbox property [TotalAmount] still has the old value but the editable textbox which I modified contains the new value I entered. Why does the disabled textbox not contain the javascript updated value?
I tried using
ModelState.Remove("TotalAmount");
in the action method above, but as I already figured it didn't work.
Any clues, tips?
Thanks for your time....
HTML input elements such as textboxes that have the disabled="disabled" attribute will never send their values to the server when the form is submitted. If you want to send the value to the server while still disabling the user from changing it you could make the textbox readonly:
<%= Html.TextBoxFor(model => model.TotalAmount, new { #readonly = "readonly" }) %>
Disabled inputs are never sent in a form submit, try using readonly attribute instead or hidden inputs
Disabled fields don't get posted. Try having a hidden form field that will send the value to the server, and set both TotalAmount and the hidden form field. On the server, use the value for the hidden field instead.
On a side note, since this looks like the order total, this is something I would recalcuate on the server rather than opening up the possibility of someone hacking the html and getting a discount on their product.
EDIT:
To the other's points, I'd forgotten about the readonly attribute. That will work too.
If you change it to use readonly rather than disabled, then this should give you the same functionality, but post the value.
Browsers don't post values back in disabled input controls, as you've discovered. Probably the easiest way to work around this is to hook onto form submission, and re-enable the input as the form is being submitted; the user won't have a chance to edit the value, and it should get posted with the rest of the request.
i think the last issue described it : please check it out :
Retrieving the value of a asp:TextBox

How to mimic MVC's checkbox -> bool model binding?

I've got an editor template which renders out a checkbox:
#Html.CheckBoxFor(model => model.Follow)
Which renders something like this:
<input checked="checked" data-val="true" data-val-required="The Follow field is required." id="Follow" name="Follow" type="checkbox" value="true" />
<input name="Follow" type="hidden" value="false" />
AFAIK the hidden field is something to do with catering when an unchecked box isn't sent to the server or something.
Anyway, if i take a look at the Request.Form["Follow"] when the checkbox is checked, i see a value of "true,false".
How do i coerce a bool from this value? Do i simply ignore the second field? (e.g the hidden field).
I'm doing this is a base controller (protected method, invoked from child controller), so i don't have a strongly-typed view model, only the raw Request object.
Can anyone help? Or alternatively, if someone could point me to where in the MVC source code this happens, i could take a look myself, but not sure where to start looking.
You are correct the hidden field is just so the form will be submitted to the server. Because if the form had just checkboxes that are not checked then nothing will be submitted and the server would not know to set them to false.
You only require 1 hidden field per form, you do not need one per checkbox. But if your making your own control it is hard to tell if a hidden textbox is already on the field or not. If you know you are always going to have a textbox or select list etc somewhere else on your forms you do not need a hidden textbox at all
You can rename your hidden textbox to anything name it "dummy" or something different to the checkbox name so Request.Form["Follow"]; will only return the value of the check box not need to split. You never need to check the value of the "hidden textbox".
On a side note you shouldn't be using Request.Form["Follow"] you Action method should have a parameter like this instead "bool? follow"
MVC helper renders checkbox input control with two input fields, the checkbox and the hidden, because the browser do not send a value for checkbox input field if the checkbox is not selected. If you do not use auto mapping, you need to parse the input value that you receve from your form.
Use this simple rule to detect the checkbox:
var rawFollow = Request.Form["Follow"];
if (rawFollow.Contains("true"))
{
// do something
}
As far as i know, the extra hidden field is because if the checkbox is NOT checked, that input will not be submitted with the form and therefore we need the hidden field with the value of false.
So the only solution is can think of is this:
var rawFollow = Request.Form["Follow"];
var rawFollows = rawFollow.Split(',');
if (rawFollows.Count() > 1)
{
rawFollow = rawFollows[0];
}
But this seems hacky (and what about the order of the elements on the page, what if for some reason the hidden field was FIRST, then it would always evaluate to false), which is why i'm wondering how the MVC source does this.

How to get the selected value of a dropdown in the MVC View itself

I have a drop down in a MVC View, which is some thing like this:
Html.DropDownList(id, Range(0,10)
.Select(x => new SelectListItem {Text = x, Value = x}))
In the view itself, I need the selected value of this drop down. I know that I can access that in a JavaScript, but I am looking for a way to get it in the view itself from the drop down properties or something like that.
How can I access it? I tried to figure out some thing from intellisense but nothing relavant showed up, help is much appreciated.
Edit: I want the value after a few lines after the declaration of the drop down, I know that I can access it from JavaScript and by posting the form, Is there noway to access it on the view itself ?
Edit2: If its not possible to access it in view, please explain the reason, I am more interested in knowing it.
Thanks.
After reading at your question, it sounds like you want to have the drop down list supply a value for a lower section of the same page.
First and foremost, you will need to place the DropDownList within a form construct, as in:
<% using (Html.BeginForm("ProcessValue", "ThisPage")) { %>
<%= Html.DropDownList("DropID", Range(0, 10).Select(a=>new SelectListItem { Text = x, Value = x }) %>
<input type=submit value="Submit" />
<% } %>
You need to set up a few things ahead of time:
You have to have a submit button, or a similar construct, in order to retrieve the value of the DropID variable.
You need to set up an controller method that will handle the processing of the value, then redirect back to the original page with the selected value in the page's ViewData.
Finally, you need to set up the view so that the post-processing section will only display if you have a valid value in the DropID variable.
It's not as simple as just placing a DropDownList in a view and then using that value later on in the page. You have to get the controller involved to manage the data transport and you have to set up the single view to handle multiple states (ie. before the value is selected and after the selection takes place).
To get the selected value you could use either javascript or a controller action to which the form containing the select box is submitted.
The selected value will be in the FormCollection or QueryString collection with the name of the DropDown's ID in the controller action that receives the form submission from this view. You can either submit the values with a classic POST or GET or via AJAX, but you have to wire up a server-side action that processes that input.
There is a SelectList class as well wich allows you to define wich item will be selected.. and knowing that - you will know selected value..
Also.. if no value is selected explicitly, dropdowns tend to select the first item in the list.

Resources