How to make IDs of components (Div, a, h1, etc) of a webpage Dynamic (variable?) using MVC2? - asp.net-mvc

I am trying to do the following:
The object I give to the Viewpage has a list, I do a foreach in the HTML and I create a number of components. Now, I want the IDs of those components to somehow be linked to the object from the List.
(The reason I am trying to do this is because I want to show a button, when they press that button the shown content will change and they should see something else, I will use javascript to achieve this)
Therefor I am trying to make the id of those components dynamic, by for example stating
id="button <%= item.id%>" however this does not seem to work. I have searched alot on google but I haven't found a solution yet which is why I turn to you guys.
I'll link my code as well, I deleted some of the parts that were unnecessary (but added the javascript):
<script type="text/javascript">
function AlterPanel(thePanel) {
var panel = document.getElementById("region"+thePanel);
panel.style.display = 'block';
var button = document.getElementById("button"+thePanel);
button.style.display = 'none';}
</script>
<%foreach (TeamDTO team in Model.List.Teams)
{ %>
<a id="button<%= team.Number %>" onclick="AlterPanel(<% team.Number%>)">
Add member</a>
<div Visible="false" id='region<%= team.Number %>' runat="server">
Please select one:
<%: Html.DropDownListFor(V => V.memberID, new SelectList(Model.members, "ID","Name")) %>
</div>
<% } %>
I eagerly await a reply and thank you in advance.

I guess your Queastion is:
-you have some "button DropDownList" pair, button is visiable, DropDownList is invisible, now if user click the button then DropDownList will showup.
OK, now your View maybe :
<%foreach (TeamDTO team in Model.List.Teams)
{ %>
<a onclick="AlterPanel(<% team.Number%>)">
Add member</a>
<div id="region<%= team.Number %>" style="display:none">
Please select one:
<%: Html.DropDownListFor(V => V.memberID, new SelectList(Model.members, "ID","Name")) %>
</div>
<% } %>
I use JQuery in javascript part like this:
<script type="text/javascript">
function AlterPanel(thePanel) {
$("#region" + thePanel.toString()).css("display", "block");
}
</script>
Don't forget include the following file in View():
<script type="text/javascript" src="<%= Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"></script>
if the answer is not what you want, let mt know and I can help you~ :)

Related

hide/show div using radiobuttons in ROR

<%= f.radio_button :newCustomer, "Male",:value=>'NewCustomer',:checked=>true%>
`<%= f.radio_button :customer, "Female",:value=>'Customer'%>`
<div id="first"></div>
<div id="second"></div>
I am new in rails.I have two radiobuttons and two div.When i click NewCustomer i want to hide first div and when i click on the Customer show the hidden div.I want to do this in only Ruby code.Is there any radiobutton click event like in .net
You can achieve it by Javascript / JQuery / Ajax in rails:
Example:
HTML
<input type="radio" name='thing' value='valuable' data-id="female" />
<input type="radio" name='thing' value='valuable' data-id="male" />
<hr />
<div id="female" class="none">Div for Male</div>
<div id="male" class="none">Div for Female</div>
CSS:
.none {display:none;}
JQuery
$(':radio').change(function (event) {
var id = $(this).data('id');
$('#' + id).addClass('none').siblings().removeClass('none');
});
Working Fiddle
Pipeline
To further Gagan's answer, you'll want to include your Javascript in the asset_pipeline:
#app/assets/javascripts/application.js
$(document).on("change", ".radio", function(){
// gagan's code here
});
--
Turbolinks
Something to note is the importance of the javascript "delegation" - when you use Rails applications with Turbolinks.
Because of the way in which Turbolinks will just update the <body> tag of your page, many JS event bindings will actually become invalid, preventing your application from loading correctly.
To fix this, you need to be able to either delegate your DOM events from a "container" element (typically document), or by encapsulating your code in Turbolinks events like so:
#app/assets/javascripts/application.js
var change = function() {
$(".radio").on("change", function(){
//Stuff here
});
};
$(document).on("page:load ready", change);

text displaying in every form field

i'm making an Ember app with a Rails back end. In one of the templates, I list the available teams from a database and beside each team put a form field for the user to enter some textual information. If I enter information in one form field, the text appears in all of the form fields (kind of like a multiple cursor experience). That's one problem. Also, when I submit the button to attend one of the conferences, nothing's happening in the controller. I'm wondering if this is a related problem as Ember might think I'm trying to submit from multiple forms at one time due to the fact that these forms are acting as if they're the same form.
Can you see what I'm doing wrong?
<script type="text/x-handlebars" id="conferences">
<div class='span4'>
{{#each item in model}}
<li> {{#link-to 'conference' item}}
{{ item.name }}
{{ partial 'conferences/form'}}
{{/link-to }}</li>
{{/each}}
</ul>
</div>
<div class="span4 offset4">
{{ outlet}}
</div>
</script>
Inserted Form
<script type="text/x-handlebars" id="conferences/_form">
<form class="form-horizontal" {{action "attend" on="submit"}}>
<div class="controls">
{{input value=username type="text"}}
</div>
<button type="submit" class="btn">attend</button>
</form>
</script>
Conferences controller
App.ConferencesController = Ember.ObjectController.extend({
actions: {
attend: function() {
console.log('this is not logging, & no indication rails route is posted to)
$.post("/join_conference_path", {
username: this.get("username"),
}).then(function() {
document.location = "/";
}, function() {
}.bind(this));
}
}
});
Having all input values synced to the same text happen due to fact that each input value is bound to the same property username.
This happens because all _form partials are rendered in the same context which is in your case App.ConferencesController. To make them render in individual context use itemController argument for each helper. See spec here: http://emberjs.com/api/classes/Ember.Handlebars.helpers.html#method_each
{{#each item in model itemController="conference"}}
In this case I suggest you rename your App.ConferencesController to App.ConferenceController which will represent individual context for each "item". Having it done this way your action will always use username input for specific "item" only.
Action may not trigger because by default all actions targets routes and not controllers. Try to add target="controller" attribute to action helper:
{{action "attend" on="submit" target="controller"}}

events are not triggerring after added by append method in jquery

<div class="sortable-sections">
<fieldset class="section draggable" id="flSectionType">
<div class="btn-drag section-handle hidden-view">
</div>
<div class="section-header">
<span class="section-label">Job Requirements</span> <a class="section-info" href="#more-info"
title="Minimum Education, Minimum Work Experience, Required Licenses/Certifications, Required Skills, Knowledge, and Abilities needed to perform the job.">
?</a>
</div>
<div class="sortable-items">
</div>
<a class="section-add-item hidden-view" id="addJR" href="#add-item" data-item='{"id":"addJR","template":"requirement","item_type":"Job Requirement"}'>
Add a new Job Requirement</a>
</fieldset>
<fieldset class="section draggable">
</fieldset>
<fieldset class="section draggable">
</fieldset>
<div>
The above code will generate a list of sections which can be dragged with in the sortable-sectons.
I am using the following script to remove sections manually and adding it back to sortable-sections, but it is not registering the jquery events.
var $section = $('.sortable-sections').find($('#flSectionType');
$('.sortable-sections').find($('#flSectionType').remove();
......
.......
$('.sortable-sections').append($section.val());
After appending the section, the event which are registered for the section-add-item css classes are not triggering.
Note:
instead of "on" used the "live" method. but it is not holding all attributes.
Edit:
Event code:
$('.section-add-item').on('click', function (e) {
that.addSection(this);
e.preventDefault();
});
instead of drag and drop, manually i am ordering the section on initial load.
.section-add-item must already exist when adding the event and the usage of on is wrong
$('body').on('click', '.section-add-item', function (e) {
});
instead of the body you can add another parent of .section-add-item that already exists before .section-add-item is created.

I Want To Give A Unique Name To Divs Which Are Rendering Dynamically

I Am Using asp.net mvc3 . I am rendering a partial view by using foreach loop . So the thing i want to do is that i have a div in my partial view every time when partial rendered a new div is placed into the page . I just want to give every div a unique name . Can Anyone Help Me Out ??????
Thanks In Advance
Just make sure you have something in the model used by your partial view that is unique - then in your partial view all you need is
<div name="div_#(Model.SomeUniqueId)"></div>
If there is nothing appropriate in the model, you can use the ViewBag:
#{
var i = 0;
foreach (var item in Model.Items) {
ViewBag.UniqueId=i++;
Html.RenderPartial("PartialView", item);
}
}
in your partial view, you could have the div defined as per below:
<div id="<%=Guid.NewGuid().ToString() %>"></div>
that way, you don't have to care about the model doing any extra lifting to populate the div id. also, note that i used id as the unique placeholder. divs don't have a 'name' attribute, so be careful to make a note of that.
You need to create DIV dynamically with the help of javascript
Following is the sample code that will help you
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Create DIV Dynamically Using JavaScript</title>
<script type="text/javascript" language="javascript">
function DynamicDiv() {
var dynDiv = document.createElement("div");
dynDiv.id = "divDyna";
dynDiv.innerHTML = "Created using JavaScript";
dynDiv.style.height = "20px";
dynDiv.style.width = "300px";
dynDiv.style.backgroundColor = 'gray';
document.body.appendChild(dynDiv);
}
</script>
</head>
<body>
<div>
<input id="Button1" type="button"
value="Using JS" onclick="DynamicDiv();" />
</div>
</body>
</html>

Ajax actionlink

I had user control in MVC ASP.NET which list the comments for particular image. I had given delete link with every comment. Now i want to delete that comment using Ajax link. Please tell me how can I use Ajax?
This is my user control and I am calling controller action on delete link:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ListComment.ascx.cs" Inherits="gConnect.Views.Shared.ListComment" %>
<li>
<div class="question-info">
<div class="votes count"></span><span><% Response.Write("<img src=../../images/" + ViewData.Model.Logo_url.ToString() + " width=75 height=100 >");%> </div>
<div class="views "><span><%= ViewData.Model.Username.Substring(ViewData.Model.Username.IndexOf("-")+1) %></span></div>
<div class ="deletem" ><span><%= Ajax.ActionLink("Delete", "DeleteComment/" + ViewData.Model.Username.Substring(0, 2) + "." + ViewData.Model.Id, new AjaxOptions(UpdateTargetId = "comments"))%></span></div>
<div class="question">
<h3 class="title"><%= Html.Encode(ViewData.Model.Comment )%></h3>
</div>
</div>
</li>
Use jQuery:
<script type="text/javascript">
function deleteComment(id) {
$.post(
"/MyController/DeleteAction",
{ id : id }
function (data) {
// do some gui updates
});
}
</script>
And use in a link:
<a onclick="deleteComment(<%= CommentId %>); return false;" href="#">Delete</a>
Use an Update Panel. It will capture the post back from your delete link and asyncronously reload the content.
Take a look at http://www.asp.net/ajax/documentation/live/Tutorials/CreatingPageUpdatePanel.aspx for an example.
Hope that helps.
Gavin
First, make sure that your delete link posts a form. Your question is not clear about this, but since you say that you are using a delete link I am guessing that you are doing this with a GET. Actions that modify resources should be done via POST, not GET.
Once you've done that, you can use the jQuery AJAX form plug-in to do the post via AJAX. It's quite simple, and once you have a working form to do that delete, you will find converting its to use the AJAX plug-in to submit the form instead very straightforward. Just follow the examples on the site.

Resources