I need to insert some JavaScript code inside a UserControl that I load from an Ajax call via jQuery Ui Tabs. Let me explain...
This is my View (with jQuery loaded)
<script type="text/javascript">
$(document).ready(function () {
$("#tabs").tabs({
cache: false,
});
getContentTab (1);
});
function getContentTab(index) {
var url='<%= Url.Content("~/Home/getUserControl") %>/' + index;
var targetDiv = "#tabs-" + index;
$.get(url,null, function(result) {
$(targetDiv).html(result);
});
}
</script>
<div id="tabs">
<ul>
<li>Nunc tincidunt</li>
<li>Proin dolor</li>
<li>Aenean lacinia</li>
</ul>
<div id="tabs-1">
</div>
<div id="tabs-2">
</div>
<div id="tabs-3">
</div>
</div>
With these lines of code I call the Ajax function to load the content into a DIV.
This is the Action from the controller:
public ActionResult getUserControl(int num)
{
return PartialView("TestUC", num);
}
And this is the UserControl...
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
Number... <span id="testSpan"><%=Model.ToString() %></span>!!
<input type="button" value="Click me!!" onclick="message();" />
<script type="text/javascript">
function message(item) {
alert($("#testSpan").html());
}
</script>
The problem is that the message() function returns always 1 (instead of returning the correct number).
My question is... How should I add the script to my UserControl in order to have my code running correctly?
I'm just guessing here.
I guess your problem is that when a tab is loaded, it stays in the DOM even if you open another one (i.e. If the #1 is the default, it will remain loaded even if you click on the second one).
If this is happening, when you call the message function, there will be multiple elements with the id "testSpan", and the jQuery selector $("#testSpan") will return the first of them.
I suppose this is just some test code, but for this particular case I would go with adding the <%= Model.ToString() %> as an argument to the javascript function.
Again, I'm just guessing about the behavior of the jquery-ui tabs() function.
Regards
Try Adding script like this
<script type="text/javascript" defer="defer">
function message(item) {
alert($("#testSpan").html());
}
</script>
Related
I am using JQuery tabs in my Asp.Net/C# app.
I am modelling my approach after this article. The JQuery is outside of my
<asp:UpdatePanel ID="UpdatePanel1"...></asp:UpdatePanel>
wrapper while the html components are inside.
Whenever I click a button, my tabs completely lose their CSS styling and I see all of the tab contents, rather than just the
<div id="current-tab">
for that tab.
Why is this happening and how do I fix it?
My guess is that its related to post-back or the update panel somehow, but I am not sure why the added C# code under page_load doesn't keep the selected tab current on post-back when the button is fired.
ASPX
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/start/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
var tabs = $("#tabs").tabs({
activate: function (e, i) {
selected_tab = i.index;
}
});
selected_tab = $("[id$=selected_tab]").val() != "" ? parseInt($("[id$=selected_tab]").val()) : 0;
tabs.tabs('select', selected_tab);
$("form").submit(function () {
$("[id$=selected_tab]").val(selected_tab);
});
...
</script>
....
<table>
<tr>
<td style="padding: 5px;">
<div id="tabs">
<ul>
<li>Tier 1</li>
<li>Tier 2</li>
<li>Tier 3</li>
<li>Tier 4</li>
</ul>
<div class="tab-content">
<div id="tab-1">
...
</div>
<div id="tab-2">
...
</div>
<div id="tab-3">
...
</div>
<div id="tab-4">
...
</div>
</div>
</div>
<asp:HiddenField ID="selected_tab" runat="server" />
</td>
</tr>
</table>
C#
protected void Page_Load(object sender, EventArgs e)
{
...
selected_tab.Value = Request.Form[selected_tab.UniqueID];
...
}
You are right, it has something to do with a Partial PostBack. So in order for jquery functions to work again you need to rebind it after the Partial PostBack is done.
<script type="text/javascript">
$(document).ready(function () {
buildTabs();
});
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(function () {
buildTabs();
});
function buildTabs() {
var tabs = $("#tabs").tabs({
activate: function (e, i) {
selected_tab = i.index;
}
});
selected_tab = $("[id$=selected_tab]").val() != "" ? parseInt($("[id$=selected_tab]").val()) : 0;
tabs.tabs('select', selected_tab);
$("form").submit(function () {
$("[id$=selected_tab]").val(selected_tab);
});
}
</script>
But the selected tab is a different story. You also need to store the active tab somewhere and re-apply it after the partial PostBack is done. See this answer for details.
But basically you need to store the active tab ID in SessionStorage, cookie or Hiddden input and re-apply it in prm.add_endRequest(function () {
I'm using summernote editor, and I want to retrieve its content in code behind.
I tried to use the following ways , but it returns empty(null)
1-
default.aspx
<div class="summernote" id="txtTest" runat="server"></div>
Code behind:
string content= txtTest.InnerText;
2-
default.aspx
<div class="summernote" id="txtTest" ></div>
Code behind:
string name = Request.Form["txtTest"];
Any suggestions?
Here is My code Working Perfectly
<div class="form-group">
<asp:Label ID="lblSummernote" runat="server" Text="Image" AssociatedControlID="txtSummernote" CssClass="control-label col-md-3"></asp:Label>
<div class="col-md-8">
<asp:TextBox ID="txtSummernote" runat="server" TextMode="MultiLine" Rows="2"></asp:TextBox>
<asp:Label ID="lblSum" runat="server" Text="Summernote"></asp:Label>
</div>
</div>
JavaScript
<script src="/Content/SummerNote/summernote.js"></script>
<script>
$(function () {
// Set up your summernote instance
$("#<%= txtSummernote.ClientID %>").summernote();
focus: true
// When the summernote instance loses focus, update the content of your <textarea>
$("#<%= txtSummernote.ClientID %>").on('summernote.blur', function () {
$('#<%= txtSummernote.ClientID %>').html($('#<%= txtSummernote.ClientID %>').summernote('code'));
});
});
</script>
<script type="text/javascript">
function funcMyHtml() {
debugger;
document.getElementById("#<%= txtSummernote.ClientID %>").value = $('#<%= txtSummernote.ClientID %>').summernote('code');
}
</script>
C# Code behind
protected void btnSubmit_Click(object sender, EventArgs e)
{
lblSum.Text = txtSummernote.Text;
}
Have you considered using a <textarea> to handle this as opposed to a <div>? Usually they are a bit easier to use with respect to storing values (as they are designed to do so) :
<textarea id="txtTest" runat="server"></textarea>
One of the ways that you might handle this would be to register an event using Summernote's available API to set the HTML content for your <textarea> element whenever focus was lost (e.g. the onblur) :
<script>
$(function () {
// Set up your summernote instance
$("#txtTest").summernote();
// When the summernote instance loses focus, update the content of your <textarea>
$("#txtTest").on('summernote.blur', function () {
$('#txtTest').html($('#txtTest').summernote('code'));
});
});
</script>
Since you are likely going to be storing HTML content within the element, you'll likely want to ensure that .NET doesn't think you are trying to exploit it. You can do this by either explicitly setting this page to ignore that process by updating the ValidateRequest property of your page :
<%# Page ... ValidateRequest = "false" %>
Or you could try simply escaping the content that is being set :
$('#txtTest').html(escape($('#txtTest').summernote('code')));
Here is how I got it working.
ref it as a class
class="summernote"
$(document).ready(function () {
$('.summernote').summernote();
});
I have a 2 pages.
Master Page
Default page (inherited from master page)
I have a menu in the master page & I need to click some menu item & when it's clicked I need some element (span) to be visible in default page.
There's no error in below code, but the expected result did not happen.
MasterPage:
<li id="lgbtn" style="float:right">Login</li>
<script>
$('#lgbtn').live('click', function (e) {
$('span4').show();//<-- this span is in Default page
});
</script>
Default.aspx:
<div class="span4" style="visibility:hidden">
<form name="form-area" class="form-area" runat="server">
//Some content here
</form>
</div>
In JQuery if you want to get element based on class then you have to write syntax like below
$('.ClassName')
and to get element based id then
$('#ControlId')
Jquery's .show is the same as saying display: block;
In order to solve this you could change it using
$('.span4').css("visibility" , "visible");
Or you could change the html to be as follows:
<div class="span4" style="display: none;">
<form name="form-area" class="form-area" runat="server">
//Some content here
</form>
</div>
1)you missed dot for class
2)you visiblity style so show didn't work in that case so please use css style visibility visible
$('.span4').css("visibility" , "visible");
try this
$('#lgbtn').live('click', function (e) {
if($('.span4').is(":visible")){
$('.span4').css("visibility" , "hidden");
}
else{
$('.span4').css("visibility" , "visible");
}
});
another way
<div class="span4" style="display:none">
$('#lgbtn').live('click', function (e) {
if($('.span4').is(":visible")){
$('.span4').show();
}
else{
$('.span4').hide();
}
});
simplest way to do you also change in html
<div class="span4" style="display:none">
$('#lgbtn').live('click', function (e) {
$('.span4').toggle();
});
first you know about what is the difference between visibilty and display in css
visibility: hidden hides the element, but it still takes up space in
the layout.
display: none removes the element completely from the document. It
does not take up any space, even though the HTML for it is still in
the source code.
You can see the effect of these style properties on this page. I
created three identical swatches of code, and then set the display and
visibility properties on two so you can see how they look.
Try to use that code:
$('#lgbtn').live('click', function (e) {
$('.span4').show();//<-- this span is in Default page
});
use
like
<script>
$('#lgbtn').live('click', function (e) {
$('.span4').css("visibility" , "visible");
});
</script>
DEMO
UPDATED DEMO WITH toggle()
For toggle() use
toggle
html
<li id="lgbtn" style="">Login</li>
<div class="span4" style="display:none">asds</div>
JS
$( document ).ready(function() {
$( "#lgbtn" ).click(function() {
alert("clicked");
$('.span4').toggle();
});
});
My requirement is like I need to display the partial view in dynamic div based on the user presses the Add another button. I tried the below code but I can't achieve it.
<html>
<head>
<title>Index</title>
<script type="text/javascript" src="../../Scripts/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="../../Scripts/jquery-ui-1.8.11.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var i = 0;
$("#chkAccecpt, #btnAccept").click(function () {
i++;
var divElement = "<br /><div id='container"+i+"'"+"> </div>";
$("#frmAccept").append(divElement);
$("#container1").load('#Url.Content("../../Views/Shared/UserInfoPartialView.cshtml")');
});
});
</script>
</head>
<body>
<div id="MainContent">
<form id="frmAccept" method="post" action="#">
<input type="checkbox" id="chkAccecpt" value="1" /> AddAnother
<br />
<input type="button" id="btnAccept" value="Add Another" />
<br />
<div id="userDetailsInfoContainer" class="Container">
#Html.Partial("~/Views/Shared/UserInfoPartialView.cshtml")
</div>
// Here I need the dynamic container1 div with that partial view controls also
</form>
</div>
</body>
</html>
I would consider fetching the partial view using Ajax
$.get("/urlToPartialViewAction",function(data){
$("#container1").html(data);
});
This will put in the view for you and insert it into a container of your choosing.
Just make sure the action returns a PartialView
Why are you calling from server
just clone container
$('#container').clone().attr("id","container1").appendTo('#frmAccept');
and you can't access view directly from browser , you have to add action for it.
You can easily do this using JQuery's Ajax method. It also allows for parameter to be send to the action.
$.ajax({
url: "#Url.Action("YourActionName", "YourControllerName")",
//data: {param1: value1, param2: value2} //add your parameters here
success: function (data) {$("#container1").html(data)},
error: $("#container1").html("")
)}
I want to have a menu that when I click replaces the content of a "main" div with content from a mvc view. This works just fine if I use a .aspx page, but any master.page content is then doubled (like the and any css/js). If I do the same but uses a .ascx user control the content is loaded without the extras, but if any browser loads the menu item directly (ie search bot's or someone with JS disabled), the page is displayed without the master.page content.
The best solution I've found so far is to create the content as a .ascx page, then have a .aspx page load this if it's called directly from the menu link, while the ajax javascript would modify the link to use only the .ascx. This leads to a lot duplication though, as every user control needs it's own .aspx page.
I was wondering if there is any better way of doing this? Could for example the master.page hide everything that's not from the .aspx page if it was called with parameter ?ajax=true?
We've solved this by using a baseController class that all controllers inherit from, and using an override for OnActionExecuted:
/// <summary>
/// Changes the masterpage to a slim version in AjaxRequest
/// </summary>
/// <param name="filterContext"></param>
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
var action = filterContext.Result as ViewResult;
if (action != null && Request.IsAjaxRequest())
{
action.MasterName = "Ajax";
}
base.OnActionExecuted(filterContext);
}
The "Ajax" master page is a then a simple masterpage with only 1 contentPlaceHolder. This works fine as long as all aspx pages that can be called with ajax only uses this placeholder.
What about making an ActionMethod that changes what it renders depending on the type of http request it gets? So if it is an ajax request it would render the ascx but if it is not, then it can render the whole view (or redirect to another action that renders the whole view)?
something like
public ActionResult Section1()
{
if (Request.IsAjaxRequest())
{
return PartialView("section1.ascx");
}
return View("section.aspx");
}
and i guess section.aspx coud have inside a RenderPartial(section1.ascx) (so you dont do the page twice).
Here is an example of the method I use with great success:
In the View:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<Namespace.Stuff>>" %>
<asp:Content ID="Content3" ContentPlaceHolderID="head" runat="server">
<script type="text/javascript">
$(document).ready(function(){
$("#optionsForm").submit(function() {
$("#loading").dialog('open');
$.ajax({
type: $("#optionsForm").attr("method"),
url: $("#optionsForm").attr("action"),
data: $("#optionsForm").serialize(),
success: function(data, textStatus, XMLHttpRequest) {
$("#reports").html(data); //replace the reports html.
$("#loading").dialog('close'); //hide loading dialog.
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$("#loading").dialog('close'); //hide loading dialog.
alert("Yikers! The AJAX form post didn't quite go as planned...");
}
});
return false; //prevent default form action
});
});
</script>
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<div id="someContent">
<% using (Html.BeginForm("Index", "Reports", FormMethod.Post, new{ id = "optionsForm" }))
{ %>
<fieldset class="fieldSet">
<legend>Date Range</legend>
From: <input type="text" id="startDate" name="startDate" value="<%=ViewData["StartDate"] %>" />
To: <input type="text" id="endDate" name="endDate" value="<%=ViewData["EndDate"] %>" />
<input type="submit" value="submit" />
</fieldset>
<%} %>
</div>
<div id="reports">
<%Html.RenderPartial("ajaxStuff", ViewData.Model); %>
</div>
<div id="loading" title="Loading..." ></div>
</asp:Content>
In the Controller:
public ActionResult Index(string startDate, string endDate)
{
var returnData = DoSomeStuff();
if (Request.IsAjaxRequest()) return View("ajaxStuff", returnData);
return View(returnData);
}