How do I conditionally add in a div and attributes? - asp.net

Here is some code on my ASP.NET site. I initially wanted to write
if((n%4)==0) {
<div>
}
//code
if((n%4)==0) {
</div>
}
but ASP.NET wouldn't have it. It had a compile error. It appears it ignores } until I close the div. So I ended up with the below. The if statement causes me the same problem. I know I can conditionally have values by writing class="#(cond?"val":"")" but that only works for values I don'
t know how to conditionally have checked in there. Having the same line written 4 times is pretty ridiculous how do I write this properly?
<div>
#for (int i = 1, n = 0; i < 32; i <<= 1, ++n)
{
if ((looking & i) != 0)
{
<input type="checkbox" name="SomeName" value="#i" id="SomeName_#i" checked>
}
else
{
<input type="checkbox" name="SomeName" value="#i" id="SomeName_#i">
}
<label for="SomeName_#i">#TestApp.Controllers.HomeController.enumFriendlyName[n]</label><br />
}
</div>
<div>
#for (int i = 32, n = 4; i < 256; i <<= 1, ++n)
{
if ((looking & i) != 0)
{
<input type="checkbox" name="SomeName" value="#i" id="SomeName_#i" checked>
}
else
{
<input type="checkbox" name="SomeName" value="#i" id="SomeName_#i">
}
<label for="SomeName_#i">#TestApp.Controllers.HomeController.enumFriendlyName[n]</label><br />
}
</div>

I assume you are talking about razor here. I'll start with attributes.. the trick is to use the html helper rather than writing the html by hand.
#Html.Label("Name", "LabelText")
#Html.CheckBox("Name", isChecked)
Also, for the CheckBox and other helpers you can pass and htmlAttributes anon function, if the value you specify for the attribute evals to null, the attribute won't be included in the rendered html.
What are you doing with the divs? Perhaps if you tell us what you want to do we can suggest something. Are you trying to stripe, because you can do that with CSS.
So, rather than the code duplication you could possible use a partial as the content for each div:
<div class="left">
#Html.Partial(_controls, model)
</div>
<div class="right">
#Html.Partial(_controls, model)
</div>
Or something. I may have the syntax wrong, but basically you can pass a model to your partial which can contain the range of items you want.
The model can be like new { start = 1, finish = 32 }

Related

show thankyou message on submit

Hello I'm trying to get my contact form to display a thank you message after the message has been sent.
I looked around but the stuff I find looks more complex than what I think i need.
I think it's something i'm missing about the event listener and how this form works.
Here's my code:
.thanks {
display: none;
}
<div class="form-wrap">
<form class="contact-form" action="https://getsimpleform.com/messages?form_api_token=aa0a1c58e87ea8816ba9ff7d7a71d0ef" method="post">
<!-- all your input fields here.... -->
<div class="name-email">
<input class="contact-field contactform-name" type='text' name='name' placeholder="Name" required/>
<input class="contact-field contact-form-email" type="email:" name="email" placeholder="e-mail" value="" required>
</div>
<textarea class="contact-field" name="message" rows="20" cols="80" placeholder="Your Message" required></textarea>
<input class="contact-field submit" type='submit' value='Send' />
</form>
</div>
<div class="thanks">
<h1>Thanks for the message!</h1>
</div>
<script>
function displayThanks() {
document.querySelector(".thanks").style.display = "block";
document.querySelector(".contact-form").style.display = "none";
}
document.querySelector(".submit").addEventListener("submit", displayThanks)
</script>
I could make it work on click, but that would mean that even if they don't send a message and just click submit they will get thank you (FOR WHAT!?)
Thanks!
M
You are mixing client side logic with server side logic. It's hard to answer your question because we don't know, what the action "action="https://getsimpleform.com/messages?form_api_token=aa0a1c58e87ea8816ba9ff7d7a71d0ef" in your form tag is doing.
It might be usefull to validate the form, before you consider to submit it. You can do this by using the click event of the submit button in combination with preventDefault like this (Just an Example, you could even use RegEx for emails and stuff):
document.querySelector(".submit").addEventListener('click', function(e) {
var userInputName = document.getElementsByName("name")[0].value,
userInputEmail = document.getElementsByName("email")[0].value,
userInputMessage = document.getElementsByName("message")[0].value;
if (userInputName.length > 0 && userInputEmail.length > 0 && userInputMessage.length > 0)
{
document.querySelector(".thanks").style.display = "block";
document.querySelector(".contact-form").style.display = "none";
}
else
{
e.preventDefault();
}
}, false);
I would recommend to use IDs instead of names though, because IDs are unique and don't require a node list or ambiguous jQuery. Than you can use something like this: userInputName = document.getElementById("name").value;
And don't forget to use the right CSS for your logic. Like:
.thanks {display: none;}

How to read checkbox/radio value in freemarker?

I'm working with share forms in alfresco and trying to read the values of ticked checkboxes and checked radio buttons form a form. I extended both the user creation and userprofile form with these input controls and so far I have been unsuccessful at reading the textual values of said controls. Below is a snippet of code:
<div class="row">
<span class="label"><input id="${el}-input-spokenEnglish" type="checkbox" name="spokenLanguages" value="${msg("label.anglais"!"")?html}" /> ${msg("label.anglais")}</span>
<span class="label"><input id="${el}-input-spokenSpanish" type="checkbox" name="spokenLanguages" value="${msg("label.espagnol"!"")?html}" /> ${msg("label.espagnol")}</span>
<span class="label"><input id="${el}-input-spokenGerman" type="checkbox" name="spokenLanguages" value="${msg("label.allemand"!"")?html}" /> ${msg("label.allemand")}</span>
<span class="label"><input id="${el}-input-spokenChinese" type="checkbox" name="spokenLanguages" value="${msg("label.chinois"!"")?html}" /> ${msg("label.chinois")}</span>
<br/>
<span class="label">${msg("label.otherLanguages")} : </span>
<span class="input"><input id="${el}-input-spokenLanguages" type="text" size="30" maxlength="256" value="" <#immutablefield field="spokenLanugages" /> /> </span>
</div>
unfortunately I get nothing so far from whatever is returned and would gladly appreciate some insight into this.fre
If you look at userprofile.get.html.ftl, you'll see the following snippet:
<script type="text/javascript">//<![CDATA[
var userProfile = new Alfresco.UserProfile("${args.htmlid}").setOptions(
{
This means it's triggering a client-side JS file from Alfresco, in this case profile.js (see the head file). So just adding some input fields isn't enough.
You need to extend the client-side JS file.
In the function onEditProfile it gets the Dom elements.
But that's just for showing the actual fiels 'after' it's saved.
In profile.js you'll see: form.setSubmitAsJSON(true); that you have a json object from which you can get your fields.
And in userprofile.post.json.ftl it does a loop on the user.properties:
for (var i=0; i<names.length(); i++)
{
var field = names.get(i);
// look and set simple text input values
var index = field.indexOf("-input-");
if (index != -1)
{
user.properties[field.substring(index + 7)] = json.get(field);
}
// apply person description content field
else if (field.indexOf("-text-biography") != -1)
{
user.properties["persondescription"] = json.get(field);
}
}
user.save();
This probably means that you haven't extended the contentmodel of the cm:person object with your new properties.

how to synchronize two controls?

I have two exactly radio button lists in my page, top and bottom. If I select a radio button in the top list, I would like the bottom list make the same change. Is there any way I could achieve this synchronization?
My radio button lists are in a content page.
<asp:RadioButtonList ID="rblVerification1" runat="server" RepeatDirection="Horizontal">
<asp:ListItem Value="V">Verified</asp:ListItem>
<asp:ListItem Selected="True" Value="NV">Not Verified</asp:ListItem>
</asp:RadioButtonList>
Update:
I wrote following javascript function, but it doesn't work. The first alert return 34, a werid number, I am expecting 2. The second alert return undefined. Can anybody tell what I did is wrong?
function rblVerificationClicked(source, destination) {
alert(source.length);
var selectedValue;
for (var x = 0; x < source.length; x++) {
if (source[x].checked) {
selectedValue = source[x].value;
break;
}
}
alert(selectedValue);
for (var x = 0; x < destination.length; x++) {
destination[x].checked = false;
}
for (var x = 0; x < destination.length; x++) {
if (destination[x].value == selectedValue) {
destination[x].checked = true;
break;
}
}
}
In page_load, I added
rblVerification.Attributes.Add("OnClick", string.Format("rblVerificationClicked('{0}', '{1}');", rblVerification.ClientID, rblVerification1.ClientID));
rblVerification1.Attributes.Add("OnClick", string.Format("rblVerificationClicked('{0}', '{1}');", rblVerification1.ClientID, rblVerification.ClientID));
Resolved:
I found what caused the problem.
asp:RadioButtonList render as input type=”radio” HTML elements.
So to get asp:RadioButtonList client id, call getElementsByTagName(“input”) which will return an array of radio buttons.
The easiest way is to do this via JavaScript. I created some example code below:
The html:
<div id="list1">
<input id="item1" type="radio" name="list1"/>Item 1
<input id="item2" type="radio" name="list1"/>Item 2
<input id="item3" type="radio" name="list1"/>Item 3
<div>
<br/>
<div id="list2">
<input id="item1" type="radio" name="list2"/>Item 1
<input id="item2" type="radio" name="list2"/>Item 2
<input id="item3" type="radio" name="list2"/>Item 3
<div>​
The JavaScript:
$("input[name=list1]:radio").bind("change", function(e) {
var chk = $("div#list2")
.children("input[id=" + $(this).attr("id") + "]");
chk.attr("checked", true);
});
​I also created an JsFiddle for it so you can see it in action.

knockout.js boolean data-binding issues with radio buttons

I'm currently doing the following to compensate for boolean's not mapping well to radio buttons. I am stuck binding 1 and 0 to the value (instead of true and false) because of how the fields are read out of the observables. The value of Pref1/Pref2 come as true/false boolean values from the server. The key here is I want to not only data-bind the checked value of the radio button to match the true/false in the object, but I also want the boolean value of true/false to be written back into the GraduationClass object. My compensation code is not only ugly, but not scalable.
<input type="radio" value="1" name="radioGroup" data-bind="checked: Pref1" />Yes
<input type="radio" value="0" name="radioGroup" data-bind="checked: Pref2" />No
Save
function SiteSettingsViewModel() {
var self = this;
this.saveGraduationClass = function(graduationClass) {
// hack until i get a custom radio button binding
if (graduationClass.Pref1() == 1) {
graduationClass.Pref1(true);
} else {
graduationClass.Pref1(false);
}
if (graduationClass.Pref2() == 1) {
graduationClass.Pref2(true);
} else {
graduationClass.Pref2(false);
}
// ...ajax call to save graduationClass to the server
}
function GraduationClass(data) {
var self = this;
ko.mapping.fromJS(data, {}, this);
}
Here is example from knockoutJs website, that demonstrate how to use radio buttons with
"checked" attribute:
<p>Send me spam: <input type="checkbox" data-bind="checked: wantsSpam" /></p>
<div data-bind="visible: wantsSpam">
Preferred flavor of spam:
<div><input type="radio" name="flavorGroup" value="cherry" data-bind="checked: spamFlavor" /> Cherry</div>
<div><input type="radio" name="flavorGroup" value="almond" data-bind="checked: spamFlavor" /> Almond</div>
<div><input type="radio" name="flavorGroup" value="msg" data-bind="checked: spamFlavor" /> Monosodium Glutamate</div>
</div>
<script type="text/javascript">
var viewModel = {
wantsSpam: ko.observable(true),
spamFlavor: ko.observable("almond") // Initially selects only the Almond radio button
};
// ... then later ...
viewModel.spamFlavor("msg"); // Now only Monosodium Glutamate is checked
</script>
But I dont understand why you use two objects - "Pref1" and "Pref2" fro one radiobutton group "radioGroup"? In this case you just could use one object as in an example used "spamFlavor".
So, please, describe more ditaily what you want to bind: one radiobuttons group by one selected value, or something else.
Also you could use computed observables to calculate different values, please see example.

ASP.NET MVC3 C# - CSS by condition

Same foreach loop I have been posting about for days :) I'm almost done :)
I now need to style the differing show and hide posts so that if they are 'hide' they need to be red. So I research and I can to that in CSS with classes. Can anybody advise how to sort out an if statement?
#foreach
(var post in Model.tb_SH_Forum_Posts.OrderBy(o => o.Post_Date))
{
using (Html.BeginForm("Hide", "Post", new { id = post.Post_ID }))
{
<input type="submit" name = "hidePosts" value="Hide" />
}
using (Html.BeginForm("Show", "Post", new { id = post.Post_ID }))
{
<input type="submit" name = "showPosts" value="Show" />
}
PSEUDO
if private_id = 2
<div class ="HIDE">
<fieldset>
<p class="post_details">At #post.Post_Date By #(post.Anon == true ? "Anonymous" : post.Username)
</p>
#post.Post_Desc
</fieldset>
</div>
ELSE
<div class ="SHOW">
<fieldset>
<p class="post_details">At #post.Post_Date By #(post.Anon == true ? "Anonymous" : post.Username)
</p>
#post.Post_Desc
</fieldset>
</div>
}
As always, thank you for your time/guidance
Try this:
<div <%: private_id == 2 ? "class=HIDE" : "class=SHOW" %> >
#if (private_id == 2)
{
<div class ="HIDE">
}else
{
<div class ="SHOW">
}
Ideally, you would like to create an HTML helper to handle that, since no logic should be used in Views.
http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs
Here is a Microsoft's article about custom helpers. Basically it's a class, where you pass something from the view, and then you include all the logic in there, and return something back to your view.

Resources