Reference between .aspx and .cs - c#

How can I build a reference between a button event on a .aspx site and a function class .cs?
This is the .aspx page:
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent1" Runat="Server">
<form id="form1" runat="server">
<div class="contentText">
<div class="row">
<label for="name">Name:</label>
<input type="text" id="name" name=""><br><br>
</div>
<div class="row">
<label for="address">Address:</label>
<input type="text" id="address" name=""><br><br>
</div>
<div class="row">
<label for="phone">Phone:</label>
<input type="tel" id="phone" name=""><br><br>
</div>
<div class="row">
<label for="email">Email:</label>
<input type="email" id="email" name="">
</div>
</div>
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
<asp:GridView ID="GridView1" runat="server" >
</asp:GridView>
</div>
</form>
</asp:Content>
And here you can see my class .cs.
public class Login
{
protected void Button1Click(object sender, EventArgs e)
{
makedatatable();
}
private void makedatatable()
{
DataTable dt = new DataTable("MyTable");
DataColumn column = new DataColumn();
column.DataType = System.Type.GetType("System.Decimal");
column.AllowDBNull = false;
column.Caption = "Price";
column.ColumnName = "Prices";
dt.Columns.Add(column);
DataRow row;
for(int i = 0; i < 10; i++)
{
row = dt.NewRow();
row["Prices"] = i + 1;
dt.Rows.Add(row);
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
}

The OnClick="Button1_Click" attribute in your markup tells the system which method in the server side code to execute when the form is posted back due to the click of that button. You can either rename your Button1Click to Button1_Click or add a nandler that calls Button1Click.

If it is ASP.Net Website, you are missing autowireup and codefile attributes in your .aspx page
<%# Page Language="C#" AutoEventWireup="true" CodeFile="class.cs" %>
If it is ASP.NET web application, You would have a designer.cs file auto generated for you. Then in the aspx file you can Inherit the class name
<%# Page Language="C#" AutoEventWireup="true" Inherits="MyNamespace.Login" %>

Related

I want to show data from model in asp c#

I am using this
private RepoMember repoMember = new RepoMember();
public List<Member> mem { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
mem = repoMember.GetAll().ToList();
}
}
RepoMember is the generic repository and GetAll() works as the name getAll to get all the members.
I am using this in aspx file
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<% foreach (Member m in mem)
{ %>
<div class="abc">
<div class="pqr">
<asp:Label Text="<%=m.Id%>" runat="server" ID="lblEmpName"></asp:Label>
</div>
</div>
<% } %>
</div>
</form>
But it shows <%=m.Id%> in the webpage.
I want to show the list of Ids on the webpage.
I am new to asp.net.
Please help.
I am using Entity Framework with MySql Database.
Edit:
Got that I can not use asp label for that but below is working
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<div>
<% foreach (Member m in mem)
{ %>
<div class="abc">
<div class="pqr">
<div><%=m.Id%></div>
</div>
</div>
<% } %>
</div>
</form>
I do not understand why...

How to change the css styles dynamically

I am trying to change the css style of the repeater to a different color on different status. The expected output is to print 6 different statuses like: In progress, complete, withdrawn so on.. Currently it has a single color, so it shows one color only. the challenging part here is to change the color dynamically based on the status. how do I achieve this? Currently it pulls the style based on "status noAction text-center" class below. Should I make any changes in the code behind or is it just a front end css change. Can someone provide me an example please.
.aspx code:
<div class="row">
<asp:Repeater ID="rptStatuses" runat="server">
<ItemTemplate>
<div class="col-md-4 col-sm-4">
<div class="status noAction text-center">
<div class="banner">
<asp:Label runat="server"> <%# Eval("ID") %></asp:Label>
</div>
<div class="label"><%# Eval("Name") %></div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>
.cs code relevant part
private void GB()
{
var surveyId = 55;
var stateLabels = _manageDatasets.GetStateLabels(surveyId);
List<Status> statusesList = new List<Status>();
foreach (var sl in stateLabels)
{
if (sl.Key != -1)
statusesList.Add(new Status { ID = sl.Key.ToString(), Name = sl.Value }
);
}
this.rptStatuses.DataSource = statusesList;
this.rptStatuses.DataBind();
}
I think what you want to do is change the class in the your html and just use the embedded code to be able to dynamically change the banner color, etc. based on the status. The embedded code that you want would look something like this -
<div class="col-md-4 col-sm-4">
<% if(status == "noAction") { %>
<div class="status noAction text-center">
<div class="banner">
<asp:Label runat="server"> <%# Eval("ID") %></asp:Label>
</div>
<div class="label"><%# Eval("Name") %></div>
</div>
<% } %>
If you have any column in you table from where repeater is getting datasource then that would be pretty easy to do
something like that
<asp:Repeater ID="rptStatuses" runat="server">
<ItemTemplate>
<div class="col-md-4 col-sm-4">
<div class='<%# Convert.toInt32(eval("ActionColumnName"))==1 ? "status In progress text-center" : Convert.toInt32(eval("ActionColumnName"))==2 ? "status complete text-center" : Convert.toInt32(eval("ActionColumnName"))==3 ? "status withdrawn text-center" : "status noAction text-center" '>
<div class="banner">
<asp:Label runat="server"> <%# Eval("ID") %></asp:Label>
</div>
<div class="label"><%# Eval("Name") %></div>
</div>
</div>
</ItemTemplate>
</asp:Repeater>

C# Server tags cannot contain <% ... %> constructs

I have this code :
<div class="detailBox">
<div class="actionBox">
<ul class="commentList">
<%
foreach (System.Data.DataRow drow in members.Rows)
{
%>
<li>
<div class="commentText">
<span><%= drow["nume_user"] %></span>
<asp:Button ID="deleteButton" CssClass="btn btn-danger btn-xs" runat="server" OnClick="deleteMember" Text="Elimina" CommandArgument="<%= drow["id"] %>" />
</div>
</li>
<%
}
%>
</ul>
</div>
</div>
I don't know why I get this error Server tags cannot contain <% ... %> constructs. when I want to give CommandArgument the value of drow["id"], how can I pass this variable to the code behind when I click on the button ?
EDIT
And the code behind that's being executed when I click the button:
protected void deleteMember(object sender, EventArgs e)
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["GroupsConnString"].ToString();
var argument = ((Button)sender).CommandArgument;
Response.Write(argument);
if (argument != null)
{
MySqlConnection conn = new MySqlConnection(connString);
conn.Open();
MySqlCommand comm = conn.CreateCommand();
comm.CommandText = "DELETE FROM app_groups.users_groups_leg WHERE id = " + argument;
int result = comm.ExecuteNonQuery(); //here you will get the no.of rows effected
conn.Close();
}
}
I think you should use <%# %> to switch between c# and html. So your code should be
<div class="detailBox">
<div class="actionBox">
<ul class="commentList">
<%#
foreach (System.Data.DataRow drow in members.Rows)
{
%>
<li>
<div class="commentText">
<span><%= drow["nume_user"] %></span>
<asp:Button ID="deleteButton" CssClass="btn btn-danger btn-xs" runat="server" OnClick="deleteMember" Text="Elimina" CommandArgument="<%= drow["id"] %>" />
</div>
</li>
<%#
}
%>
</ul>
</div>
</div>

Compiler error on asp.net page with form submit

I try to firean submit via an asp button. I got the error that there is no definition vor SubmitBtn_Click in 'ASP.default_aspx.
BootstrapASP.Master:
<%# Master Language="C#" AutoEventWireup="true" CodeBehind="BootstrapASP.master.cs" Inherits="Shift.BootstrapASP" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Shift</title>
<link type="text/css" rel="stylesheet" href="css/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="css/main.css" />
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
<asp:ContentPlaceHolder ID="head" runat="server"></asp:ContentPlaceHolder>
</head>
<body>
<div>
<asp:ContentPlaceHolder ID="ContentMain" runat="server"></asp:ContentPlaceHolder>
</div>
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/interactive.js"></script>
</body>
</html>
Default.aspx:
<%# Page Title="Shift" Language="C#" MasterPageFile="~/BootstrapASP.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Shift.WebForm1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"></asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentMain" runat="server">
<div class="container content-wrapper">
<form role="form" runat="server">
<div class="row">
<div class="col-md-4 col-md-offset-7">
<asp:LinkButton ID="SubmitBtn" runat="server" OnClick="SubmitBtn_Click" CssClass="btn btn-danger btn-lg pull-right">
<span class="glyphicon glyphicon-import"></span> Senden
</asp:LinkButton>
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-1">
<h1>Set Down</h1>
<hr />
<div id="down-form-holder">
<div class="form-group">
<label for="old-pc-ci">Computer CI*</label>
<input type="text" class="form-control" name="old-pc-ci" id="old-pc-ci" />
</div>
<div class="form-group">
<label for="old-mon-ci">Monitor CI*</label>
<input type="text" class="form-control" name="old-mon-ci[]" id="old-mon-ci" />
</div>
</div>
<button type="button" id="old-add-monitor" class="btn btn-default btn-sm pull-right">
<span class="glyphicon glyphicon-plus"></span> Monitor
</button>
</div>
</div>
</form>
</div>
</asp:Content>
In the Default.aspx.cs I created an eventhandler for the "SubmitBtn_Click"
Default.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Shift
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
void SubmitBtn_Click(Object sender, EventArgs e)
{
}
}
}
Methods in C# are private by default, so your click handler is not visible from the markup. Common practice is to make them protected:
protected void SubmitBtn_Click(Object sender, EventArgs e)
Your event needs to be protected, the way you have it is defaulting to private:
protected void SubmitBtn_Click(Object sender, EventArgs e)
{
}
protected void SubmitBtn_Click(object sender, EventArgs e)
{
}
<asp:LinkButton ID="SubmitBtn" runat="server" OnClick="SubmitBtn_Click" CssClass="btn
btn-danger btn-lg pull-right">
<span class="glyphicon glyphicon-import"></span> Senden</asp:LinkButton>

form does not return all updated values while editing

Hi I have the following view that gets the values for the form fields from a viewdata that contains an instance of a class ApplicationSettingEntity. the ApplicationSettingEntity class contains an instance of a machineentity class as one of the attributes. The form is populated by values from
item.Id
item.Key
item.Machine.Name
When I edit the values the form returns the updated values for item.Id and item.Key but not item.Machine.Name
I inspected the value of item.Machine.Name as I am hydrating the form and It is setting the value of the text box correctly but data posted back for item.Machine is null when I hit the save button. What am I doing wrong?
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<%# Import Namespace="AppSettings.Web.Models" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Edit Application Setting
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<strong style="color: Black;">
<div>
<% if (ViewData["ApplicationSetting"] != null)
{
var item = (ApplicationSettingEntity)ViewData["ApplicationSetting"];
%>
<%=Html.ActionLink("Back to List", "Index",
new
{
controller = "ApplicationSettings",
Applications = item.Id,
Machines = item.Machine.Id
})%>
</div>
<%=Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.")%>
<%
using (Html.BeginForm((bool)ViewData["IsAdd"] ? "SaveAdd" : "SaveEdit", "ApplicationSettings"))
{%>
<fieldset>
<legend><strong>Application Name:</strong>
</legend>
<p>
<label for="Id" style="font-weight: bold;">
Application Setting Id:</label>
<%=Html.TextBox("Id", item.Id)%>
<%=Html.ValidationMessage("Id", "*")%>
</p>
<p>
<label for="Key" style="font-weight: bold;">
Application Setting Key:</label>
<%=Html.TextBox("Key", item.Key, new {style = "width:400px;"})%>
<%=Html.ValidationMessage("Key", "*")%>
</p>
<p>
<span style="font-weight: bold;">Machine Name: </span>
<%=Html.TextBox("MachineName", item.Machine.Name)%>
</p>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
<%
}%>
<div>
<%=Html.ActionLink("Back to List", "Index",
new
{
controller = "ApplicationSettings",
applicationId = item.Application.Id,
machineId = item.Machine.Id
})%>
</div>
<%
}%>
</asp:Content>
You get the value of the post in the item MachineName of the form collection, because that is the first param of Html.TextBox

Categories