Button OnClick="btnSave_Click" does not work in MVC application - asp.net-mvc-2

I am new to MVC architecture and I am struggling to get the Button onclick. Please help me trace the issue. I have a Telerik TreeView control, which is populated. Some of the nodes have child nodes and some of them doesn't.
Please let me know what changes need to be made to fix the issue
Here I am struggling to get it working.
<%# Page Language="C#" MasterPageFile="~/Views/Shared/PostLogin.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<applications>>" %>
<%# Import Namespace="ApplicationGrps" %>
<%# Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>
<script runat="server" type="text/javascript">
protected void Page_Load()
{
ApplicationGrps.Visible = true;
ApplicationGrps.DataSource = ODS1;
ApplicationGrps.DataFieldID = "ApplicationName";
ApplicationGrps.DataFieldParentID = "ParentID";
ApplicationGrps.DataBind();
BindCheckedTags(ApplicationGrps);
}
protected void BindCheckedTags(RadTreeView treeView)
{
// Displays the checked nodes
}
protected void ODS2_Selecting(object sender, ObjectDataSourceSelectingEventArgs e)
{
e.InputParameters["ClientID"] = ViewData["ClientID"];
}
protected void btnSave_Click(object sender, EventArgs e)
{
//Iterate through the tree and get all the nodes that are checked and submit it.
}
</script>
<asp:Content ID="Content2" ContentPlaceHolderID="HeadContent" runat="server">
<link href="<%: Url.Content("~/Content/script-libraries/jquery-ui-1.7.2.custom/css/smoothness/jquery-ui-1.7.2.custom.css") %>"
rel="stylesheet" type="text/css" />
<script src="<%: Url.Content("~/Scripts/jquery-1.4.1.js") %>" type="text/javascript"></script>
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<form id="form1" runat="server" method="post">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<telerik:RadTreeView id="AppModulesTreeView" runat="server" CheckBoxes="True" Visible="true" >
</telerik:RadTreeView>
<asp:ObjectDataSource ID="ODS1" runat="server"
SelectMethod="GetAllApplicationModules"
TypeName="ELS.BOS.Services.EntitlementProxy.EntitlementServiceClient">
</asp:ObjectDataSource>
<asp:ObjectDataSource ID="ODS2" runat="server"
SelectMethod="GetApplicationModMappedByClientID"
TypeName="ELS.BOS.Services.EntitlementProxy.EntitlementServiceClient"
onselecting="ODS2_Selecting">
<SelectParameters>
<asp:Parameter Name="ClientID" Type="String" />
</SelectParameters>
</asp:ObjectDataSource>
<%-- <telerik:RadButton runat="server" onclick="btnSave_Click"
Text="Save">
</telerik:RadButton>
<telerik:RadButton ID="btnCancel" runat="server" Text="Cancel"
>
</telerik:RadButton>--%>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="btnSave_Click" />
</div>
</form>
</asp:Content>
Please let me know if I need to use javascript or jquery to get this working. Please show me some samples on how to fire btnSave_click on button control click.
Thanks!

<asp:Button ID="Button1" runat="server" Text="Button" OnClick="btnSave_Click" />, asp:ObjectDataSource, ScriptManager, ... in an ASP.NET MVC application?
No.
In an ASP.NET MVC applications you don't use server side controls (no runat="server"). You don't PostBack. There is no ViewState. There is no code behind. There are no events. There are no script managers. There are no object data sources. All this is specific to WebForms and is no longer used in MVC.
In an ASP.NET MVC application you have a Controller, a Model and a View. The view contains standard HTML markup which could be generated with the aid of HTML helpers. To call the controller you could use a normal link:
<%= Html.ActionLink("link text", "actionName", "controllerName") %>
The controller contains actions which manipulate the model and choose the view to be rendered by passing it all the information it needs to show.
I would strongly recommend you start reading the tutorials here: http://asp.net/mvc about how MVC works and familiarize yourself with the very basics of this framework.

Related

How do I change the default value of a raddropdownlist from outside the control?

I have a raddropdown list and need different default values for when it is used in different pages. This is the code for the raddropdown in th user control:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="UploadExcel.ascx.cs" Inherits="EntityFramework.Controls.UploadExcel" %>
<%# Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
<telerik:RadStyleSheetManager ID="RadStyleSheetManager1" runat="server" />
<div style="height: 50px;"></div>
<telerik:RadDropDownList ID="RadDropDownList1" runat="server" Width="200">
<Items>
<telerik:DropDownListItem Selected="true" Text="STL010_gen_and_load_settlement" />
<telerik:DropDownListItem Visible="false" Text="LeasingSolarEdge" />
</Items>
I have 2 pages which use this user control and need different values to be selected when the page loads. The page code:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="STL010Upload.aspx.cs" Inherits="SunseapEBT.Web.UploadParameter.STL010Upload" %>
<%# Register Src="~/Control/Upload/UploadExcel.ascx" TagPrefix="uc1" TagName="UploadExcel" %>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<uc1:UploadExcel runat="server" ID="UploadExcel" />
</asp:Content>
Is there any way to change user control values from the page when it loads the control?
Found a way to change it from the user control by getting the url of the page that requested it.
if (Request.Url.PathAndQuery.Contains("STL010"))
{
RadDropDownList1.Enabled = false;
RadDropDownList1.SelectedIndex = 0;
}
else if (Request.Url.PathAndQuery.Contains("Solar"))
{
RadDropDownList1.Enabled = false;
RadDropDownList1.SelectedIndex = 1;
}

How to: Find a control ID in insert/edit mode of a Telerik RadGrid

I have an application that have been developed before I started working and the datepickers are custom. we recently migrated to Windows 8 and the custom datepickers are not working anymore. So I started to change them for jquery-ui datepicker and everything was going like I was expecting. But now I face a problem. some of those custom datepickers are in the edit/insert mode of the Telerik RadGrid. My jquery-ui datepicker pop-up when the text-box receive focus with some java-script using the control's id. I have no problem making the new control appear in edit/insert mode with the right value in it. My problem is that I cannot find the control's id of the edit/insert mode of the RadGrid to pop-up the datepicker when the control receive focus. Any help would be greatly appreciated.
Please try with the below code snippet.
ASPX
<head runat="server">
<title></title>
<telerik:RadStyleSheetManager ID="RadStyleSheetManager1" runat="server" />
</head>
<body>
<form id="form1" runat="server">
<telerik:RadScriptManager ID="RadScriptManager1" runat="server">
</telerik:RadScriptManager>
<script type="text/javascript">
function TextBoxFocus(obj) {
alert(obj.id);
//Access client ID here
}
function RadTextBoxFocus(sender, args) {
alert(sender.get_id());
//Access client ID here
}
</script>
<telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
</telerik:RadAjaxManager>
<div>
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" OnNeedDataSource="RadGrid1_NeedDataSource" OnItemDataBound="RadGrid1_ItemDataBound">
<MasterTableView>
<Columns>
<telerik:GridBoundColumn DataField="ID" HeaderText="ID" UniqueName="ID"></telerik:GridBoundColumn>
<telerik:GridTemplateColumn UniqueName="Name" DataField="Name">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<telerik:RadTextBox ID="TextBox1" runat="server" Text='<%# Eval("Name") %>'>
<ClientEvents OnFocus="RadTextBoxFocus" />
</telerik:RadTextBox>
</EditItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridEditCommandColumn></telerik:GridEditCommandColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</div>
</form>
</body>
</html>
ASPX.CS
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(1, "Name1");
dt.Rows.Add(2, "Name2");
dt.Rows.Add(3, "Name3");
RadGrid1.DataSource = dt;
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridEditableItem && e.Item.IsInEditMode)
{
GridEditableItem item = e.Item as GridEditableItem;
TextBox TextBox1 = item["ID"].Controls[0] as TextBox;
TextBox1.Attributes.Add("onfocus", "TextBoxFocus(this);");
}
}
Let me know if any concern.
I managed to access the control , I don't know if I did something very bad since it is pretty simple.
ASPX
<asp:TextBox ID="BoxILookFor" runat="server" Text='<%# Eval("myValue") %>' />
ASPX.CS
protected void myGrid_ItemDataBound(object sender, GridItemEventArgs e)
{
if ((e.Item is GridEditableItem) && (e.Item.IsInEditMode))
{
GridEditableItem myItem = (GridEditableItem)e.Item;
TextBox myBox = (TextBox)myItem.FindControl("BoxILookFor");
string myID = myBox.ClientID.ToString();
myGrid.Controls.Add(new LiteralControl("<script type='text/javascript'>$('#" + myID + "').datepicker();</script>"));
}
}
But now I face another problem, my textbox (datepicker) saves an empty string no mather what value (what date) I choose.

Is it possible to repeat content from one placeholder multiple times?

Is it possible to use the content of a ContentPlaceHolder in multiple places in a master page?
For example, I often want to do something like:
<html>
<head>
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server" /></title>
<link rel="Stylesheet" href="../../Content/Corporate.css" />
</head>
<body>
<div id="header">
<h1>I'd like to reuse the TitleContent ContentPlaceHolder content here?</h1>
</div>
<div id="content">
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</div>
<div id="footer">
© 2012 Acme corp.
</div>
</body>
</html>
Answer is here, so please reward author, but to adjust it to MVC, here is what you need to do:
First: Define your own master page class (Site.Master):
<%# Master Language="C#" Inherits="MyProject.Views.Shared.MyMasterPage" %>
Second: Class content:
public class MyMasterPage : ViewMasterPage
{
protected override void RenderChildren(HtmlTextWriter writer)
{
var mainPlaceHolder = FindControl("TitleContent");
var doublePlaceHolder = FindControl("TitleContentDuplicated");
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
using (var tw = new HtmlTextWriter(sw))
{
mainPlaceHolder.RenderControl(tw);
}
var lc = new LiteralControl(sb.ToString());
doublePlaceHolder.Controls.Add(lc);
base.RenderChildren(writer);
}
}
Third: Then you can use:
<title>
<asp:ContentPlaceHolder ID="TitleContent" runat="server" />
<asp:ContentPlaceHolder ID="TitleContentDuplicated" runat="server" />
</title>

Unreadable characters displaying in ASP.NET MVC

I am trying to build a store front.
StoreViewModel
public class StoreViewModel
{
public IEnumerable<GetStoreFrontItems_Result> StoreFrontItems { get; set; }
}
Index.aspx
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<StoreViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
..:: Gods Creation Taxidermy :: Store ::..
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<div class="maintext">
<h2 class="sectionHeader2">:: Gods Creation Taxidermy : Store Items ::</h2>
<br />
At times I end up with items and mounts that the owner never came to pick up, so I put them up for sale to help generate
some revenue for Gods Creation Taxidermy.
<strong>NOTE:</strong> Now before you freak out and think I'm going to sell your mount remember the items for sale are several years old
and the owner simply didnt make the final payment or for some reason left it here.
<% Html.DataList(Model.StoreFrontItems).Columns(7).Item(item =>
{
item.Template(storeItems =>
{%>
<div style="margin-right:45px; line-height:150%;">
<span><%: Html.ActionLink(storeItems.CategoryName, "List", new { #animal = storeItems.CategoryName });%></span>
</div>
<%-- <div style="margin-right:45px; line-height:150%;">
<span><% = galleryImage.ItemName%></span>
</div>
<div style="margin-right:45px; line-height:150%;">
<span><% = galleryImage.ItemPrice%></span>
</div>--%>
<%});
}).Render(); %>
</div>
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="MetaTagsContent" runat="server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="LeftColumnContent" runat="server">
</asp:Content>
GetStoreFrontItems_Result is generated with function import. Here is the code from Index in StoreController:
[CanonicalUrlAttribute("Store")]
[CompressionFilter(Order = 1)]
[CacheFilter(CacheDuration = 120, Order = 2)]
public virtual ActionResult Index()
{
GodsCreationTaxidermyEntities context = new GodsCreationTaxidermyEntities();
var viewModel = new StoreIndexViewModel() { StoreFrontItems = context.GetStoreFrontItems() };
return View(viewModel);
Here are some screenshots, one showing the error and the other showing what gets displayed.
As far as the error is concerned from what you have shown as code it is impossible to answer why does it happen (although the error message seems more than pretty self explanatory). As far as the garbage characters are concerned they are caused by the Compression filter you are using on your action. Here's a blog post which explains perfectly fine the reason and how to fix it.
The proposed solution is to put the following in your Global.asax to cancel the effect of ASP.NET stripping the custom compression HTTP headers that your CompressionFilter might have added in case of an exception:
protected void Application_PreSendRequestHeaders()
{
// ensure that if GZip/Deflate Encoding is applied that headers are set
// also works when error occurs if filters are still active
HttpResponse response = HttpContext.Current.Response;
if (response.Filter is GZipStream && response.Headers["Content-encoding"] != "gzip")
response.AppendHeader("Content-encoding", "gzip");
else if (response.Filter is DeflateStream && response.Headers["Content-encoding"] != "deflate")
response.AppendHeader("Content-encoding", "deflate");
}

Too many JavaScript and CSS files on my ASP.NET MVC 2 Master Page?

I'm using an EditorTemplate DateTime.ascx in my ASP.NET MVC 2 project.
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime>" %>
<%: Html.TextBox(String.Empty, Model.ToString("M/dd/yyyy h:mm tt")) %>
<script type="text/javascript">
$(function () {
$('#<%: ViewData.TemplateInfo.GetFullHtmlFieldId(String.Empty) %>').AnyTime_picker({
format: "%c/%d/%Y %l:%i %p"
});
});
</script>
This uses the Any+Time™ JavaScript library for jQuery by Andrew M. Andrews III.
I've added those library files (anytimec.js and anytimec.css) to the <head> section of my master page.
Rather than include these JavaScript and Cascading Style Sheet files on every page of my web site, how can I instead include the .js and .css files only on pages that need them--pages that edit a DateTime type value?
First idea that comes to mind =>
Template:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<DateTime>" %>
<%: Html.TextBox(String.Empty, Model.ToString("M/dd/yyyy h:mm tt")) %>
<script type="text/javascript">
$(function () {
MakeSureAnyTimeIsIncluded();
$('#<%: ViewData.TemplateInfo.GetFullHtmlFieldId(String.Empty) %>').AnyTime_picker({
format: "%c/%d/%Y %l:%i %p"
});
});
</script>
masterpage or shared external JS file:
function MakeSureAnyTimeIsIncluded(){
if (!anyTimeIsIncluded)
//document.write(<script src="correct url") something like that
anyTimeIsIncluded=true;
}
In your master:
<asp:ContentPlaceHolder ID="Scripts" runat="server" />
And in the Views (aspx) that will use the EditorTemplate/plugin:
<asp:Content ID="indexScripts" ContentPlaceHolderID="Scripts" runat="server">
<script type="text/javascript" src="anytime.js"></script>
</asp:Content>