Hello Guys i am having following code in my Content page of my master page
<%# Page Title="About Us" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="Description.aspx.cs" Inherits="Description" %>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script src="http://maps.google.com/maps?file=api&v=2&key=key&sensor=true"
type="text/javascript"></script>
<script type="text/javascript">
function initialize()
{
if (GBrowserIsCompatible())
{
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(20,30), 10);// I want to change these coordinates
map.setUIToDefault();
}
}
$(document).ready(function ()
{
initialize();
});
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<div id="main">
</div>
</asp:content>
In above code i want to fetch coordinates from code behind .
I am having coordinates in code behind ex string coor = "20,30";
so inside page load event how can i put the value of this variable in java script code.
Should I create a String literal there ? or something else.
You could store them in a property and then use them:
map.setCenter(new GLatLng(<%= Lat %>, <%= Lon %>), 10);
where Lat and Lon are two public integer properties in your code behind. You could also use methods if you will.
Related
I am getting a null reference exception when trying to FindControl on a button. I have a shopping cart setup where I have a content page (.aspx) based on a master page. On the content page, there is a placeholder control in which I am dynamically adding user controls (one control per product, each with an 'add to cart' button inside it).
When the user clicks button to add item to cart, I can add it to the cart successfully, then I am counting the number of items in the cart and if more than 1, trying to show the 'checkout' button, or if none in the cart hide it.
I am using FindControl, but getting a null reference error. Why can't it find the checkout button? My current code is below:
MASTER PAGE (template.Master):
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="template.master.cs" Inherits="OUWP.template" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head runat="server"></head>
<body>
<form id="form1" runat="server">
<asp:ContentPlaceHolder ID="m_cph_body" runat="server"></asp:ContentPlaceHolder>
</form>
</body>
</html>
CONTENT PAGE (shop.aspx)
<%# Page Title="" Language="C#" MasterPageFile="~/template.Master" AutoEventWireup="true" CodeBehind="shop.aspx.cs" Inherits="OUWP.shop" %>
<%# MasterType VirtualPath="~/template.Master" %>
<asp:Content ID="Content2" ContentPlaceHolderID="m_cph_body" runat="server">
<asp:PlaceHolder ID="Catalogue" runat="server">
<!-- this is where the user controls are dynamically generated-->
</asp:PlaceHolder>
<asp:Panel ID="pnl_Basket" runat="server">
<div>
<asp:LinkButton ID="lbtnCheckout" runat="server">Continue to Checkout</asp:LinkButton>
</div>
</asp:Panel>
</asp:Content>
USER CONTROL PAGE (PurchasableProduct.ascx)
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="PurchasableProduct.ascx.cs" Inherits="OUWP.CustomControls.PurchasableProduct" %>
<asp:UpdatePanel ID="udpBody" runat="server">
<ContentTemplate>
<asp:Panel ID="pnlPurchasableProduct" runat="server">
<asp:LinkButton ID="lbtnAddLine" runat="server" OnClick="lbtnAddLine_Click"></asp:LinkButton>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="lbtnAddLine" />
</Triggers>
</asp:UpdatePanel>
USER CONTROL CODE BEHIND (PurchasableProduct.ascx.cs)
protected void lbtnAddLine_Click(object sender, EventArgs e)
{
// try to find checkout button on parent page of control
System.Web.UI.Page page = (System.Web.UI.Page)this.Page;
LinkButton Target1 = (LinkButton)page.FindControl("lbtnCheckout");
// count the items in the cart (saved in session variable)
DataTable dt = (DataTable)Session["varDataTableCart"];
Int32 ItemCount = 0;
Int Line Quantity = 0;
foreach (DataRow dr in dt.Rows)
{
Int32 LineQuantity = Convert.ToInt32(dt.Rows[dt.Rows.IndexOf(dr)]["Quantity"].ToString());
ItemCount = ItemCount + LineQuantity;
}
// if 1 or more items in cart, try to make button visible
if (ItemCount > 0)
{
Target1.Visible = true;
}
// otherwise no items in cart, so try to hide checkout button
else
{
Target1.Visible = false;
}
}
I have also tried to get at it through the master page using the code below but that didn't work either:
MasterPage mp1 = (MasterPage)page.Master;
LinkButton Target1 = (LinkButton)mp1.Page.FindControl("lbtnCheckout");
Ok so by pure luck I tried this code and it worked and found my button. Using 'parent' of the current control.
LinkButton Target1 = (LinkButton)this.Parent.FindControl("lbtnCheckout");
I am trying to add a user control dynamically to an asp.net web page.
user control code:
<%# Control ClassName="CustomParameterView" %>
<script runat="server">
public string Value { get; set; }
public string Description { get; set; }
public string Name { get; set; }
private void Input_OnTextChanged(object sender, EventArgs e)
{
Value = Input.Text;
}
</script>
<div class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label" id="DisplayName"></label>
<div class="col-sm-3">
<asp:TextBox ID="Input" runat="server" CssClass="form-control" OnTextChanged="Input_OnTextChanged" />
</div>
</div>
</div>
I have added the register line in the .aspx file:
<%# Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="PerCHW.Valkyrie.Server.WebApplication._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<%# Reference Control="CustomParameterView.ascx" %>
...
The problem is that this:
var control = (CustomParameterView) LoadControl("CustomParameterView.ascx");
does not compile.
I also saw people trying ti add the ASP. before the UC name but that does not work as well...
What am I doing wrong?
It looks like you are not adding the control to a PlaceHolder.
In the .aspx page add a PlaceHolder:
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
And then add the Control to the PlaceHolder in code behind:
var control = (CustomParameterView)LoadControl("~/CustomParameterView.ascx");
PlaceHolder1.Controls.Add(control);
Make sure this code is called every time the page is loaded, so don't put it inside a !IsPostBack check or the Control will be gone after PostBack.
I really dont understand why this simple example doesnt work :S
I have a WebApplication in which I have a script :
function myAlert() {
$("#Button1").click(function () {
alert("Hello world!");
});
}
In my asp page, I have this simple code
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Graph.aspx.cs" Inherits="WebApplication.Graph" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" Width="100px"/>
</asp:Content>
And finally I register the script in the cs :
protected override void OnPreLoad(EventArgs e)
{
Page.ClientScript.RegisterClientScriptInclude("jQuery",
ResolveUrl(#"Scripts\jquery-1.4.1.js"));
Page.ClientScript.RegisterClientScriptInclude("jMyAlert",
ResolveUrl(#"Scripts\MyAlert.js"));
// check if the start up script is already registered with a key
if(!Master.Page.ClientScript.IsStartupScriptRegistered("jMyAlert"))
{
// since it is not registered, register the script
Master.Page.ClientScript.RegisterStartupScript
(this.GetType(), "jMyAlert", "myAlert();", true);
}
}
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "jMyAlert", "myAlert()", true);
}
I dont see what's wrong with this. I tried to include the scrit directly inside the aspx but nothing. I then try onto a simple html page and it works fine.
I want to use a plotting library using jQuery in my page so I'm very far to succeed if such a simple example causes me such a lot of problem...lol
Try checking the debug console within whatever browser you are using to see if "$" is undefined. It sounds like you are missing jquery when using the full ASP.NET approach.
The Id of that button is not going to be #Button1 because of the use of the master page. Try viewing the source to see what I mean.
To solve this, you will need to be able to see the actual Id in the JavaScript.
Something like this in your Page_Load method:
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"Button1Id", string.Format("var Button1Id = '{0}';", Button1.ClientID), true);
Will create the following in your page:
<script type="text/javascript">
//<![CDATA[
var Button1Id = 'Button1';//]]>
</script>
Which then means that your myAlert method will need to look like this:
function myAlert() {
$("#" + Button1Id).click(function () {
alert("Hello world!");
});
}
I want to double click on a cell of a gridpanel an call another
action/view with extra parameter example:
The gridpanel is in .../Student and I want to show the details of one
student in another page ex: /Student/Detail/1 double clicking on his
name, id, or wherever data is on his record.
Sorry for the bad english
I tried this
#(
Html.X().GridPanel()
.Title("Students")
.Width(550)
.Height(200)
.ForceFit(true)
.Store(Html.X().Store().Model(Html.X().Model()
.Fields(fields =>
{
fields.Add(Html.X().ModelField().Name("StudentID"));
fields.Add(Html.X().ModelField().Name("LastName"));
fields.Add(Html.X().ModelField().Name("FirstMidName"));
fields.Add(Html.X().ModelField().Name("EnrollmentDate"));
}
)
).DataSource(Model)
).ColumnModel(
Html.X().Column().Text("Student ID").DataIndex("StudentID"),
Html.X().Column().Text("Last Name").DataIndex("LastName"),
Html.X().Column().Text("First Name").DataIndex("FirstMidName"),
Html.X().DateColumn().Text("Enrollment").DataIndex("EnrollmentDate")
).DirectEvents(de =>
{
de.CellDblClick.Url = "Edit"; // also tried
de.CellDblClick.Action = "Edit";
de.CellDblClick.ExtraParams.Add(1); //static
later I'll add the StudentID here
}
)
)
The gridpanel show the data without problem but when I doubleclick on a
cell this is the request that it's sended
localhost:10782/Student/Edit?_dc=1359052548829
instead of this
localhost:10782/Student/Edit/1
I can suggest to manage an URL with a Before handler.
To remove "?dc..." from an URL, please set up DisableCaching="false".
<%# Page Language="C#" %>
<%# Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Ext.NET v2 Example</title>
<script>
var counter = 1;
</script>
</head>
<body>
<ext:ResourceManager runat="server" />
<ext:Button runat="server" Text="Test">
<DirectEvents>
<Click Url="Some URL" Before="o.url = o.rawUrl + counter++;" DisableCaching="false">
<CustomConfig>
<ext:ConfigItem Name="rawUrl" Value="Controller/Action/" Mode="Value" />
</CustomConfig>
</Click>
</DirectEvents>
</ext:Button>
</body>
</html>
I have been trying to organise my views to optimize load times by having css in the head and scripts at the end of the body.
To this end I have created masterpages that have 3 content placeholders: styles, maincontent and scripts.
With the (achieved) aim that when I render a single view with a master this neatly can collate all the shared components and specific page components into their respective places in the rendered page. The difficultly comes when I try rendering a master-detail model.
Consider the following:
I have a Master-Detail model say Order-OrderItems and views for the Order and views for the OrderItems. In an effort to be DRY and not to repeat myself (doh! I just did right then :) ) I would like to partially render the OrderItems list view in the Order header view and still achieve the correct element layout i.e: have the any specific css be rendered into the content placeholder in the head, content into the main content placeholder and scripts into my scripts content placeholder at the bottom of the body.
I have a nasty hack at the moment but wondered if there is a cleaner way of doing this.
My current hack is the equivalent of a sql cross join with a where clause in that I do a partial render of the orderitems view in each contentplaceholder of the order view and inject the name of that placeholder into the viewdata. In the orderitems view if the placeholder name does not equal the target placeholder, I return and there by only the css get rendered into the css place holder etc. To re-phrase it, I render the child three times in the parent, while in the child I return a different part of the content for each rendering.
Smells funny and not very elegant as the child has to know that it is being rendered etc.
My next thought is to try intercepting a copy of the ViewPage and taking control of the rendering using using SetRenderMethodDelegate by only calling render on the target contentplaceholder control but this is getting very tangled at this point.
Can anyone suggest a better way that maintains code re-use and optimal html output?
Some example code:
<%# Master Language="C#" ... %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Master-Detail</title>
<!--common styles-->
<link type="text/css" href="my.css" rel="stylesheet" />
<asp:ContentPlaceHolder ID="Styles" runat="server" ></asp:ContentPlaceHolder>
</head>
<body>
<!--common markup-->
<h2>Master Markup</h2>
<asp:ContentPlaceHolder ID="mainContent" runat="server"></asp:ContentPlaceHolder>
<!--common scripts-->
<script type="text/javascript" src="/scripts/my.js"></script>
<asp:ContentPlaceHolder ID="Scripts" runat="server"></asp:ContentPlaceHolder>
</body>
</html>
Order View
<%# Page Title="Order" Language="C#" MasterPageFile="~/Views/Shared/my.Master" ... %>
<asp:Content ContentPlaceHolderID="Styles" runat="server">
<style type="text/css">
/*order styles*/
</style>
<%
var partialContext = this.Html.GetViewContext("OrderDetails", "List", this.ViewData.Model.Items, this.ViewData);
partialContext.RenderContentPlaceHolder("Styles");
%>
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<h3>Order Markup</h3>
<%
var partialContext = this.Html.GetViewContext("OrderDetails", "List", this.ViewData.Model.Items, this.ViewData);
partialContext.RenderContentPlaceHolder("MainContent");
%>
</asp:Content>
<asp:Content ContentPlaceHolderID="Scripts" runat="server">
<script type="text/javascript">
/*order specific script*/
</script>
<%
var partialContext = this.Html.GetViewContext("OrderDetails", "List", this.ViewData.Model.Items, this.ViewData);
partialContext.RenderContentPlaceHolder("Scripts");
%>
</asp:Content>
Order Items View:
<%# Page Title="OrderItems" Language="C#" MasterPageFile="my.aspx" ... %>
<asp:Content ID="Content2" ContentPlaceHolderID="Styles" runat="server">
<% if (ViewData["placeHolderName"] != null && ViewData["placeHolderName"].ToString().ToLower() != "styles")
return; %>
<style type="text/css">
/*OrderItems style*/
</style>
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<% if (ViewData["placeHolderName"] != null && ViewData["placeHolderName"].ToString().ToLower() != "maincontent")
return; %>
<h4>Order Items MarkUp</h4>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="Scripts" runat="server">
<% if (ViewData["placeHolderName"] != null && ViewData["placeHolderName"].ToString().ToLower() != "scripts")
return; %>
<script type="text/javascript">
/*Order Items script*/
</script>
</asp:Content>
Where there are a couple of extension methods:
public static ViewContext GetViewContext(this HtmlHelper htmlHelper, String controller, String viewName, Object model, ViewDataDictionary viewData)
{
var routeData = new System.Web.Routing.RouteData();
routeData.Values["controller"] = controller;
var controllerContext = new ControllerContext(htmlHelper.ViewContext.HttpContext, routeData, htmlHelper.ViewContext.Controller);
var viewEngineResult = ViewEngines.Engines.FindView(controllerContext, viewName, "Partial");
var viewData2 = new ViewDataDictionary(viewData);
viewData2.Model = model;
var viewContext = new ViewContext(controllerContext, viewEngineResult.View, viewData2, htmlHelper.ViewContext.TempData, htmlHelper.ViewContext.Writer);
return viewContext;
}
public static void RenderContentPlaceHolder(this ViewContext context, String placeHolderName)
{
context.ViewData["placeHolderName"] = placeHolderName;
context.View.Render(context, context.Writer);
context.ViewData.Remove("placeHolderName");
}
Have a look at this similar question asked some time ago:
How can I include css files from an MVC partial control?
Especially the link provided in the accepted answer is quite interesting:
http://www.codeproject.com/Articles/38542/Include-Stylesheets-and-Scripts-From-A-WebControl-.aspx
edit: You can find another blogpost of the same author updated for MVC 2 here: http://somewebguy.wordpress.com/2010/04/06/adding-stylesheets-scripts-in-asp-net-mvc2/