i'm developing a .net application using twitter bootstrap.
I'm trying to get data from .aspx.cs page to .aspx page.
Please find my code below:
strOblect.cs
public class strObject
{
public string Name { get; set; }
public string Description { get; set; }
}
.aspx.cs page:
public List<strObject> stringList = new List<strObject>();
protected void Page_Load(object sender, EventArgs e)
{
strObject ObjOne=new strObject();
ObjOne.Name="One";
ObjOne.Description ="One";
stringList.Add(ObjOne);
strObject ObjTwo=new strObject();
ObjTwo.Name="Two";
ObjTwo.Description ="Two";
stringList.Add(ObjTwo);
strObject ObjThree=new strObject();
ObjThree.Name="Three";
ObjThree.Description ="Three";
stringList.Add(ObjThree);
}
.aspx:
<asp:Panel ID="pnlData" runat="server" style="background-color:White;">
<script type="text/javascript">
$(document).ready(function () {
var valueAssigned=stringList;
});
</script>
</asp:Panel>
I'm unable to get stringList value in $(document).ready.
Please help me out to get the value.
It appears that your stringList is actually a collection of objects. In order to use it in JavaScript as such, you'll need to serialize it to a javascript object.
var valueAssigned=<%=new JavaScriptSerializer().Serialize(stringList)%>;
So that you can wind up with the following:
var valueAssigned= [{Name: "Foo", Description: "Bar"}, {...}];
Edit
JavaScriptSerializer is in System.Web.Script.Serialization - you'll either need to add this below at the top of your <%# Page
<%# Import Namespace="System.Web.Script.Serialization" %>
or specify the FQ name
var valueAssigned=<%=new System.Web.Script.Serialization.JavaScriptSerializer()
.Serialize(stringList)%>;
StuartLC's answer will be enough.JSON is very good option for that purpose. Other option can be to register client script in aspx.cs. Here is another SO question regarding that
How do I pass data from c# to jquery/javascript?
Related
i'm using the same js script call in both scenarios... one it is called from a button_click event and it works properly (changes the label text) as per below...
public void Test_OnClientClick(object sender, EventArgs e)
{
Console.WriteLine("test");
ClientScript.RegisterStartupScript(this.GetType(), "updateText", "updateText('test');", true);
}
When it is called from an event raised by a redis subscription, the same call does not work...
public void Page_Load(object sender, EventArgs e)
{
// Establish connection
redisConn = ConnectionMultiplexer.Connect(redisIP);
rbsub = redisConn.GetSubscriber();
rbsub.Subscribe(ServerRedisChannel).OnMessage(channelMessage => {
MessageHandler(channelMessage.Message.ToString());
});
}
public void MessageHandler(string cm)
{
try
{
//Test_OnClientClick(null, null);
ClientScript.RegisterStartupScript(this.GetType(), "updateText", "updateText('test');", true);
}
catch (Exception e)
{
var x = e;
}
}
I confirm it reaches the ClientScript call in MessageHandler with a breakpoint but it never reaches the debugger in the js script.
Full code below:
Default.aspx
<%# Page Title="Home Page" Async="true" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebForm._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<script type="text/javascript">
function updateText(strData) {
debugger;
document.getElementById("<%=lblTest.ClientID%>").innerHTML = strData;
}
</script>
<div class="jumbotron">
<h1>redis test</h1>
<p><asp:Label ID="lblTest" runat="server" Text="redis output"></asp:Label></p>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Test_OnClientClick"/>
<p>Learn more ยป</p>
</div>
</asp:Content>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using StackExchange.Redis;
namespace WebForm
{
public partial class _Default : Page
{
ConnectionMultiplexer redisConn;
ISubscriber rbsub;
public const string redisIP = "gptdevnj01:6379";
public const string ServerRedisChannel = "ac";
public const int redisDB = 7;
public void Page_Load(object sender, EventArgs e)
{
// Establish connection
redisConn = ConnectionMultiplexer.Connect(redisIP);
rbsub = redisConn.GetSubscriber();
rbsub.Subscribe(ServerRedisChannel).OnMessage(channelMessage => {
MessageHandler(channelMessage.Message.ToString());
});
}
public void MessageHandler(string cm)
{
try
{
//Test_OnClientClick(null, null);
ClientScript.RegisterStartupScript(this.GetType(), "updateText", "updateText('test');", true);
}
catch (Exception e)
{
var x = e;
}
}
public void Test_OnClientClick(object sender, EventArgs e)
{
Console.WriteLine("test");
ClientScript.RegisterStartupScript(this.GetType(), "updateText", "updateText('test');", true);
}
}
}
So i suppose the question boils down to calling a js script from a button_click event differs from when it is called from a subscription (or async) event?
Response to a button click happens within ASP.NET Page Lifecycle, whereas handling of an asynchronous message from a Redis subscription will most likely:
happen completely outside of that lifecycle, and
in a completely different thread.
Unless you synchronize those threads somehow (one that handles the request and one that handles received messages) - your call to ClientScript.RegisterStartupScript will go to void, to wrong client or simply fail. Please note however that the nature of asynchronous operations may require a different approach from your side rather blocking a thread to wait for a message.
Is it possible to use js variables in c# code?
This is my model:
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public int? ParentId { get; set; }
public virtual ICollection<Department> Parent { get; set; }
}
And this is my cshtml:
#model List<inspinia.models.Department>
<select name="DepartmentId" class="form-control" id="Department">
#foreach (var item in Model)
{
<option value="#item.Id">#item.Name</option>
}
</select>
<script>
$(document).ready(function () {
$("#Department").on("change", function () {
var DepartmentId = $('option:selected', this).attr('value');
//the problem in the next line.
#foreach(var item in Model.Where(x=>x.ParentId==#:DepartmentId))
{
#:alert(#item.id)
}
});
});
</script>
Well I am having error when I use
Model.Where(x=>x.ParentId==#:JAVASCRIPT VARIABLE).
Is there any way to do it or I definitely have to use ajax ?
No you can't, because the javascript code's is for clientside and razor in serverside.
You have two solutions:
1- Put all departement in list(<ul>) and use JQuery for get your data on change
2- Use jquery ajax and get data directly from controller(create controller for that)
I need call codebehind function with parameter which is instance of some Entity class from script tags in aspx page. Im created popup windows from kendo ui using kendotemplate and in this template i need my form with inputs and button used in code behind. Something like this http://demos.telerik.com/kendo-ui/grid/custom-command but when i add asp items to template tags not work for me.
My entity:
public class Person
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
public int Age { get; set; }
}
code behind function:
protected void btnAddPerson_Click(object sender, EventArgs e)
{
Person p= new Person();
// get values from three inputs
p.FirstName= personFirstName.Value;
p.LastName= personLastName.Value;
p.Age = Convert.ToInt32(personAge.Value);
...
}
i need in javascript something like this:
<script type="text/x-kendo-template" id="template">
<Asp:Input ...>
<Asp:Input ...>
<Asp:Input ...>
<Asp:Button ...>
</script>
and sorry for my english
I am building an ASP.Net Telerik Radgrid at runtime based on a passed in configuration so there is no radgrid tag on my ASPX page. I am trying to implement functionality where I can add a button to the header of the grid that will show or hide the column filters.
I am using a Command Item Template to provide the show/hide button which is appearing but when I click the button to show or hide the filters with the ShowHideFilters Javascript method using the grid.get_masterTableView() function it can not find the get_masterTableView() method on the grid object.
Any idea why this method is missing or a better alternative to achieve the behavior I require?
Telerik Radgrid Client API
JavaScript example from Telerik API
function getMasterTableView() {
var grid = $find("<%=RadGrid1.ClientID %>");
var masterTableView = grid.get_masterTableView();
}
Page
<%# Page Language="VB" AutoEventWireup="false" CodeFile="ShowGrid.aspx.vb" Inherits="ShowGrid" %>
<%# Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="ShowGrid" runat="server">
<telerik:RadScriptManager ID="ScriptManager" runat="server">
</telerik:RadScriptManager>
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
<AjaxSettings>
<telerik:AjaxSetting AjaxControlID="ConfigureGrid">
<UpdatedControls>
<telerik:AjaxUpdatedControl ControlID="ConfigureGrid" LoadingPanelID="AjaxLoadingPanel" />
</UpdatedControls>
</telerik:AjaxSetting>
</AjaxSettings>
</telerik:RadAjaxManager>
<telerik:RadAjaxLoadingPanel ID="AjaxLoadingPanel" runat="server"/>
<asp:SqlDataSource ID="PrimaryDataSource" runat="server"/>
</form>
<script type="text/javascript">
function ShowHideFilters()
{
var grid = document.getElementById("ConfigureGrid")
if (grid)
{
var masterTableView = grid.get_masterTableView();
window.alert(masterTableView.id)
}
window.alert(grid.id)
}
</script>
</body>
</html>
Code behind
Build the grid from the ground up in the Page_Init
Protected Sub Page_Init(sender As Object, e As EventArgs) Handles Me.Init
Try
BuildConfiguration()
CreateTitleObject()
CreateRadFilter()
LoadDataSource()
CreateRadGrid()
Catch ex As Exception
CreateExceptionDisplay(ex)
End Try
End Sub
Item template
Friend Class RadGridCommandItemFilterTemplate
Implements ITemplate
Protected showHideFilterButton As Button
Public Sub New()
MyBase.New()
End Sub
Public Sub InstantiateIn(ByVal container As Control) Implements ITemplate.InstantiateIn
showHideFilterButton = New Button
showHideFilterButton.EnableTheming = True
showHideFilterButton.ID = "showHideFilterButton"
showHideFilterButton.Text = "Show / Hide Filters"
showHideFilterButton.CommandName = "ShowHideFilters"
showHideFilterButton.OnClientClick = "ShowHideFilters()"
container.Controls.Add(showHideFilterButton)
End Sub
End Class
Adding the item template
grid.MasterTableView.CommandItemTemplate = New RadGridCommandItemFilterTemplate
Please check if you have proper grid id and if you use $find method. Code provided is a little messy and I'm not sure which part is invoked.
In function getMasterTableView you use $find but you have wrong id I guess. Also if this function is in javascript file then "<%=RadGrid1.ClientID %>" won't be resolved to correct id. It must be in aspx file to do so.
In function ShowHideFilters you use wrong function getElementById will return DOM object not Telerik one. Please also note that your grid has "TestGrid" id.
UPDATE:
To get master table you need to use find method. If you want more generic solution then I reccomend to add simple css class to your button. And then in onLoad event add handlers to those buttons. If you have jQuery element that is placed inside grid then you can use following function to locate grid dynamically:
function getParentGrid($element) {
var $parentGrid = $element.closest("div.RadGrid");
var parentGridId = $parentGrid[0].id;
return window.$find(parentGridId);
}
With help from Telerik support I have come up with this.
Item template
Friend Class RadGridCommandItemFilterTemplate
Implements ITemplate
Public showHideFilter As ImageButton
Public bannerTitle As Label
Private gridClientID As String
Private showFilter As Boolean = False
Private title As String = String.Empty
Public Sub New()
MyBase.New()
End Sub
Public Sub New(gridClientID As String, showfilter As Boolean, title As String)
MyBase.New()
Me.gridClientID = gridClientID
Me.showFilter = showfilter
Me.title = title
End Sub
Public Sub InstantiateIn(ByVal container As Control) Implements ITemplate.InstantiateIn
If Not String.IsNullOrWhiteSpace(title) Then
bannerTitle = New Label With {.Text = title, .CssClass = "title"}
container.Controls.Add(bannerTitle)
End If
If showFilter Then
showHideFilter = New ImageButton With {.ID = "showHideFilter",
.CommandName = "ShowHideFilters",
.CssClass = "searchButton"}
showHideFilter.Attributes.Add("onclick", (Convert.ToString("setFilter('") & gridClientID) + "'); return false;")
container.Controls.Add(showHideFilter)
End If
End Sub
End Class
Java script
<script type="text/javascript">
function pageLoad(sender, args) {
setFilter('ConfigureGrid');
}
function setFilter(gridClientID) {
var grid = $find(gridClientID);
if (grid.get_masterTableView().get_isFilterItemVisible()) {
grid.get_masterTableView().hideFilterItem();
}
else {
grid.get_masterTableView().showFilterItem()
}
}
</script>
I have c# class say options more like AjaxOptions.
public class options
{
public string Url {get;set;}
public string httpMethod {get;set}
}
and a javascript function like this
function dosomething(obj)
{
if (obj.Url!="" and obj.HttpMethod=="something")
loadsomething();
}
Now in my Controller action
public class mycontroller : controller
{
public ActionResult WhatToDo()
{
options obj = new options{Url="someurl"};
return PartialView(obj);
}
}
in my view I need this object kind of string which i should be able to pass to my method.
#model options
<script>
dosomething(#model.SomeFunctionToConverToString())
</script>
So I need this SomeFunctionToConverToString method which i will convert this object to string.
Thanks
You should be able to use it like you would any other output of a model property in your view. Just reference the property that you want to pass in the JS function.
#model options
<script>
dosomething('#(model.Url)');
</script>
See this post for more information on using Razor inside of JS
EDIT - Something that might catch you is that if your URL get's broken from the HTML encoding that Razor does using the above, you can use the #Html.Raw() function which will pass the Url property without HTML encoding it.
<script>
dosomething('#Html.Raw(model.Url)');
</script>
EDIT 2 - And another SO post to the rescue! You are going to most likely want to convert your model to JSON in order to use in a Javascript function. So...in order to do that - you will need something in your view model to handle a JSON object.
public class optionsViewModel
{
public options Options{get;set;}
public string JsonData{get;set;}
}
and in your controller:
public class mycontroller : controller
{
public ActionResult WhatToDo()
{
options obj = new options{Url="someurl"};
var myViewModel = new optionsViewModel;
myViewModel.options = obj;
var serializer = new JavaScriptSerializer();
myViewModel.JsonData = serializer.Serialize(data);
return PartialView(myViewModel);
}
}
And finally the view:
#model optionsViewModel
<script>
dosomething('#model.JsonData')
</script>
Using this method, then your function will work as expected:
function dosomething(obj)
{
if (obj.Url!="" and obj.HttpMethod=="something")
loadsomething();
}
EDIT 3 Potentially the simplest way yet? Same premise as edit 2, however this is using the View to JsonEncode the model. There are probably some good arguments on either side whether this should be done in the view, controller, or repository/service layer. However, for doing the conversion in the view...
#model options
<script>
dosomething('#Html.Raw(Json.Encode(Model))');
</script>
Try this:
<script type="text/javascript">
var obj= #Html.Raw(Json.Encode(Model));
function dosomething(obj){}
</script>
That's work for me
Client side:
function GoWild(jsonData)
{
alert(jsonData);
}
Alert print :
{"wildDetails":{"Name":"Al","Id":1}}
MVC Razor Side:
#{var serializer new System.Web.Script.Serialization.JavaScriptSerializer();}
<div onclick="GoWild('#serializer.Serialize(Model.wildDetails)')"> Serialize It </div>
there is also a syntax error
<script type="text/javascript">
dosomething("#Model.Stringify()");
</script>
note the quotes around #Model.Stringify() are for javascript, so the emitted HTML will be:
<script type="text/javascript">
dosomething("this model has been stringified!");
</script>
I would recommend you have a look at SignalR, it allows for server triggered javascript callbacks.
See Scott H site for details: http://www.hanselman.com/blog/AsynchronousScalableWebApplicationsWithRealtimePersistentLongrunningConnectionsWithSignalR.aspx
In summary thou ...
Javascript Client:
var chat = $.connection.chat;
chat.name = prompt("What's your name?", "");
chat.receive = function(name, message){
$("#messages").append("
"+name+": "+message);
}
$("#send-button").click(function(){
chat.distribute($("#text-input").val());
});
Server:
public class Chat : Hub {
public void Distribute(string message) {
Clients.receive(Caller.name, message);
}
}
So .. Clients.receive in C# ends up triggering the chat.receive function in javascript.
It's also available via NuGet.