Input hidden is built without value - asp.net-mvc-4

Weird this one.
On my .NET MVC 4 project I've added a file on App_Code who contains this method:
#helper CheckBox(string name, bool isChecked = false, string className = "") {
<div class="checkboxHolder">
<input id="#name" name="#name" type="hidden" value="#isChecked") />
<i class="#className checkboxBts fa #((isChecked) ? "fa-check-square-o" : "fa-square-o")" data-checkbox-associated="#name"></i>
</div>
}
I'm using it to style checkboxes using font-awesome, so my app checkboxes are made of an input type hidden who stores a boolean value and an icon to give feedback to users.
Weird thing is, on executing when isChecked == false, the hidden returned by this method is like:
<input id="myCheckboxId" name="myCheckboxId" type="hidden" />
There is no value at all, when I try to save it to the model an exception is thrown saying that model cannot be saved.
I've fixed it changing the method to use:
<input id="#name" name="#name" type="hidden" #((isChecked) ? "value=true" : "value=false") />
Which is working fine. However, I wonder if anyone know what could be happening on the original output.
Thank you all.

It's not entirely a duplicate, but this is answered in Why is my hidden input writing: value=“value” instead of true/false?:
if you have:
<input name="somefield" type="hidden" someprop="#(SomeBooleanExpression)"/>
[and #SomeBooleanExpression] is false it is omitted completely:
<input name="somefield" type="hidden"/>
To get around this, consider .ToString()
So, use:
<input id="#name" name="#name" type="hidden" value="value="#(isChecked.ToString())" />

Related

How can I render the input with type='text' in blazor server-side?

Here are the codes:
<EditForm OnValidSubmit="#SubmitText" id="inputText">
<InputText #bind-Value="_InputMsgModel.Msg" />
</EditForm>
After the program ran, it turned out to be this:
<form id="inputText">
<input class="valid">
</form>
Now I wanna add an attribute type="text" to the input element, how can I achieve this?
I tried to modify the code like this:
<EditForm OnValidSubmit="#SubmitText" id="inputText">
<input type="text" #bind-Value="_InputMsgModel.Msg" />
</EditForm>
Meanwhile, now visual studio reports an error:
I can not bind the model anymore.
I need to set the type to text for needing to set the keyboard in mobile correctly.
How can I solve this? Thank you.
What is wrong with this code:
<EditForm Model="#_InputMsgModel" OnValidSubmit="#SubmitText" id="inputText" >
<InputText #bind-Value="#_InputMsgModel.Msg" />
</EditForm>
Run this code with the above:
#code {
InputMsgModel _InputMsgModel = new InputMsgModel();
private void SubmitText()
{
Console.WriteLine(_InputMsgModel.Msg);
}
public class InputMsgModel
{
public string Msg { get; set; } = "My new message";
}
}
Do you see the text "My new message" in the text box ? I believe you do... All is well, and the two-way binding mechanism works well. Go and see now the Html...it's still <input class="valid"> which does not reflect the real state of the text box. Think about it...
Update: Of course you can use the following:
<EditForm Model="#_InputMsgModel" OnValidSubmit="#SubmitText" id="inputText" >
<input type="text" #bind-value="#_InputMsgModel.Msg" />
</EditForm>
Important: The error "The attribute names could not..." is triggered because you use capital "V" in #bind-Value. You should use lower case: #bind-value. This is because your using input 'Html element' here, and it has a value attribute, not a Value attribute. But when you use the InputText Component, the capital Value in #bind-Value refers to a Value property defined in the component.

Blazor checkbox binding is not working - server-side

TLDR;
It is like the string/textbox binding works just fine on input controls, but the checkbox binding backed by Boolean properties does not work. I know the binding for checkbox values needs to used a 'checked' attribute instead of a 'value' attribute, but Blazor is supposed to handle that across different control types.
I'm doing some Blazor work (server-side app) with RC1 and cannot seem to get Boolean values binding to an input checkbox control. I believe that the syntax being used is correct (see below). As a simple test, I created a new project and simply replaced the index.razor page with the sample code below. When you run it, notice:
The "Test Value" for the textbox input control initializes just fine.
The checkbox's initial value is true, but the checkbox is not checked.
Change the textbox input control's text and then change control
focus. Notice a message gets printed in the Debug window in the Output
tab of Visual Studio (Expected behavior)
Change the checkbox input control's value (checking or uncheck) and then change control focus. Notice that there no message appears in the Debug window in the Output tab of Visual Studio (Not expected behavior).
#page "/"
<div class="form-group">
<label for="last-name">Textbox Binding Test</label>
<input #bind="TestString" type="text" class="form-control" id="last-name" placeholder="Enter Last Name" />
</div>
<div class="form-group">
<label for="send-email-updates">Checkbox Binding Test</label>
<input type="checkbox" bind="#TestBool" id="send-email-updates" />
</div>
#code {
private bool _testBool = true;
protected bool TestBool
{
get { return _testBool; }
set
{
_testBool = value;
System.Diagnostics.Debug.WriteLine($"Value of {nameof(TestBool)} = {value}");
}
}
private string _testString = "Test Value";
protected string TestString
{
get { return _testString; }
set
{
_testString = value;
System.Diagnostics.Debug.WriteLine($"Value of {nameof(TestString)} = {value}");
}
}
}
This behavior was observed regardless of making the properties public, used auto-properties (no private variables), or removed the control name/id attribute values. This seems to happen regardless of whether I use the #code directive on the page or separate out a viewmodel that inherits from ComponentBase.
The bottom line is that I'm able to get text-based values when a user submits the form, but all the Boolean properties seem to remain as they were when first initialized.
When you look at both controls:
<input #bind="TestString" type="text" class="form-control" id="last-name" placeholder="Enter Last Name" />
<input bind="#TestBool" type="checkbox" id="send-email-updates" />
It is clear you are mixing bind and #bind notations, probably from older Blazor editions.
This one works in rc1:
<input type="checkbox" #bind="TestBool" id="send-email-updates" />
but in general I would argue for using the <EditForm> and related tags:
<EditForm Model="this">
<InputCheckbox #bind-Value="TestBool" />
</EditForm>

only first word from radio button selection is being returned

To get the selected option from a radio button form, I'm looking at request.vars to get the value. Following is the controller code:
def get_results():
test = request.vars['QuestionOne']
for topic in session.selectedtopics:
test = test + request.vars[topic]
return locals()
And now the code for the view:
{{extend 'layout.html'}}
<P>Please select the options that most closely approximates the actual scenario.
<br>
<form action="{{=URL('get_results')}}" method="post">
{{nameTopic =""}}
{{session.selectedtopics = list()}}
{{for topic in topics:}}
{{if nameTopic <> topic.topic.replace(" ", "_"):}}
<br><h2>{{=topic.topic}}</h2>
{{nameTopic = topic.topic.replace(" ", "_")}}
{{session.selectedtopics.append(nameTopic)}}
{{pass}}
<p><input type="radio" name={{=nameTopic}} value={{=topic.param}}>{{=topic.param}}</p>
{{pass}}
<br>
<input type="submit">
</form>
Here is the problem: I don't know the reason, but it is getting only the first word of the selected option in the radio form. For example, the option selected is "It is normal", but the var is returning only "It". Any idea why it is happening?
Thank in advance.
You need to quote the HTML attribute values:
<input type="radio" name="{{=nameTopic}}" value="{{=topic.param}}">
Without the quotes, you'll end up with final HTML like:
<input type="radio" name=some_topic value=It is normal>
The browser will interpret the value to be "It", with "is" and "normal" being invalid HTML attributes.

Javascript, and radio buttons

OK here is the deal. I have a survey that I am putting up with over 60 questions. I want to make them all mandatory. I really need to know if the group has a value, don't care what it is.
Here is what I have, but it is only giving me the first value.
<function CheckField(myFieldName, myText){
var x=document.getElementById(myFieldName).value;
window.alert(myFieldName + "1: " +x);
. . .. . .
OK so this returns the first value of 5. It does not matter what I select. All I just need to know if they selected something if not I want to mark the question with a different color so the user knows to go back and answer the question.
You can try HTML5 required:
<label><input type="radio" name="option" required /> Option 1</label>
<label><input type="radio" name="option" /> Option 2</label>
You can use it on one radio (per each name), or on all of them (see HTML5: How to use the "required" attribute with a "radio" input field).
Option 1: (EASY!)
Having the attribute "checked" set to "true" would make have a default value either way.
<input type="radio" name="option" />Option 1
<input type="radio" name="option" checked="true" />Option 2
You could also use required instead of checked attribute but some browsers don't support it like Safari.
For info on support:
required
checked
Option 2:
JSFiddle:
http://jsfiddle.net/FE7sK/2/
jQuery(function () {
jQuery('#validateOpt').bind('click', checkRadio);
})
function checkRadio() {
var isChecked = jQuery("input[type=radio]:checked").val();
var booleanVlaueIsChecked = false;
if (isChecked) {
booleanVlaueIsChecked = true;
$('#form1').submit();
} else {
alert("aaa");
}
}

MonoRail CheckboxList?

I'm trying to use a Checkboxlist in MonoRail to represent a many to many table relationship. There is a Special table, SpecialTag table, and then a SpecialTagging table which is the many to many mapping table between Special and SpecialTag.
Here is an excerpt from the Special model class:
[HasAndBelongsToMany(typeof(SpecialTag),
Table = "SpecialTagging", ColumnKey = "SpecialId", ColumnRef = "SpecialTagId")]
public IList<SpecialTag> Tags { get; set; }
And then in my add/edit special view:
$Form.LabelFor("special.Tags", "Tags")<br/>
#set($items = $FormHelper.CreateCheckboxList("special.Tags", $specialTags))
#foreach($specialTag in $items)
$items.Item("$specialTag.Id") $Form.LabelFor("$specialTag.Id", $specialTag.Name)
#end
The checkboxlist renders correctly, but if I select some and then click Save, it doesn't save the special/tag associations to the SpecialTagging table (the entity passed to the Save controller action has an empty Tags list.) One thing I noticed was that the name and value attributes on the checkboxes are funky:
<label for="special_Tags">Tags</label><br>
<input id="3" name="special.Tags[0]" value="UCampus.Core.Models.SpecialTag" type="checkbox"> <label for="3">Buy 1 Get 1 Free</label>
<input id="1" name="special.Tags[1]" value="UCampus.Core.Models.SpecialTag" type="checkbox"> <label for="1">Free</label>
<input id="2" name="special.Tags[2]" value="UCampus.Core.Models.SpecialTag" type="checkbox"> <label for="2">Half Price</label>
<input id="5" name="special.Tags[3]" value="UCampus.Core.Models.SpecialTag" type="checkbox"> <label for="5">Live Music</label>
<input id="4" name="special.Tags[4]" value="UCampus.Core.Models.SpecialTag" type="checkbox"> <label for="4">Outdoor Seating</label>
Anyone have any ideas?
Thanks!
Justin
The checkboxlist renders correctly
it seems to me that you could also render something like
<input type="checkbox" name="special.Tags" value="1"/>
<input type="checkbox" name="special.Tags" value="2"/>
which make it simpler (no index to output for the name, it will be properly resolved as an array via controller action parameter binding
also, in your sample, the fact that all checkboxes having the same value UCampus.Core.Models.SpecialTag is probably not right, you may want to output actual primary key identifier from the tags (not sure, could you display the class you are binding back on the form handling action?)
I was able to get it working by specifying the id and text attributes...
$Form.LabelFor("special.Tags", "Tags")<br/>
#set($items = $FormHelper.CreateCheckboxList("special.Tags", $specialTags, "%{value='Id', text='Name'}"))
#foreach($specialTag in $items)
$items.Item("$specialTag.Id") $Form.LabelFor("$specialTag.Id", $specialTag.Name)
#end