Nothing happens and no errors binding data from sql server to textbox - textbox

Im trying tot start with a easy setup. I try to get de data into textboxes and start with the first step. For some reason I can't bind the data to the textbox and don't received any errors. Programming is running fine, but nothing is happening when I press the button.
I tested with gridview to check the connection and that seems to be working.
I'm using MS SQL Server 2016 Express version, visual studio 2017, ASP and C#
What do I wrong? Wrong code? Connection blocked by the server?
.........................
ASPX code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="test3.aspx.cs" Inherits="test3" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server" Width="281px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Start" />
</div>
</form>
</body>
</html>
.............................
The CS code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
public partial class test3 : System.Web.UI.Page
{
public SqlConnection conn = new SqlConnection(#"Data Source=.\WDVEXPRESS;Initial Catalog=user;User ID=testaccount;Password=123test");
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand com;
string str;
conn.Open();
str = "select * from Company$ where Name = 'testuser'";
com = new SqlCommand(str, conn);
SqlDataReader reader = com.ExecuteReader();
if (reader.Read())
{
TextBox1.Text = reader["Name"].ToString();
reader.Close();
conn.Close();
}
}
}
.......................
Many thanks for the help!

Your button on aspx page is not bound to button click event on aspx.cs page. Check below code it will tell you how they got bounded -
HTML ( ASPX PAGE ) CODE
<asp:Button ID="Button1" runat="server" Text="Start" OnClick="Button1_Click" />
CS CODE
protected void Button1_Click(object sender, EventArgs e)
{
//Your Click Event Here
}

Related

Why won't the ASP.NET Webform LinkButton in my MVC project invoke its code-behind OnClick event handler?

I have a previously operational webforms project I had to include in a preexistent MVC-based solution and in it there's a LinkButton control inside a form that is now only partially working; its JavaScript event handler works perfectly fine (referenced below by OnClientClick) but the C# code-behind (lnkSubmit_Click) isn't being invoked! Why not?
My LinkButton's inside Pay.aspx:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Pay.aspx.cs" Inherits="PayUp.Pay" MasterPageFile="~/Views/Shared/Site.Master" %>
<form id="form1" runat="server" onsubmit="return validateForm();" defaultbutton="lnkSubmit" action="~/Views/Home/Pay.aspx" method="post" >
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div align="center">
<script type="text/javascript">
window.onload = function () {
hideFields();
};
</script>
<asp:UpdatePanel runat="server" id="PendingPayments1">
<ContentTemplate>
<!-- Valid form controls, blah blah.... -->
</ContentTemplate>
</asp:UpdatePanel>
<asp:Label ID="labelPayPlan" runat="server" Text="Pay Plan">
</asp:Label>
<asp:HiddenField ID="hiddenPDFForm" Value="false" runat="server" ClientIDMode="Static" />
<asp:UpdatePanel runat="server" id="PaymentInformation1">
<ContentTemplate>
<asp:LinkButton ID="lnkSubmit" runat="server" EnableViewState="false" OnClientClick="javascript: document.getElementById('hiddenPDFForm').value = 'false';"
CssClass="button" onclick="lnkSubmit_Click" onserverclick="lnkSubmit_Click" ClientIDMode="Static">Pay Up!<img alt='Pay Up!' src='images/pay.gif' style='border:0px; margin-left:6px;' />
</asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>
</form >
The code-behind does exist inside Pay.aspx.cs:
using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Configuration;
using SupportingMVCProject;
using System.Web.Mvc;
namespace PayUp
{
public partial class Pay : System.Web.Mvc.ViewPage<SupportingMVCProject.Account>
{
protected void Page_Load(object sender, EventArgs e)
{
// The code in this event handler runs just fine when I start the project!
// This code successfully receives and correctly parses my URL parameters (QN, PN, AC).
}
protected void lnkSubmit_Click(object sender, EventArgs e)
{
// The code in this event handler never gets to run!
}
}
}
My RouteConfig.cs looks like:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Http;
namespace MainMVCProject
{
public static class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{WebForm}.aspx/{*pathInfo}");
routes.MapRoute("PayUpIndex", "SupportingMVCProject/PayUp",
new { controller = "PayUp", action = "Index" }
);
// Other valid preexisting MVC routes...
// blah, blah
}
}
}
The PayUpController.cs PayUpIndex route identified above looks like the following, and it does run:
public ActionResult Index(string QN, string PN, string AC)
{
string result = "";
if (!AccessValidation(PN, out result))
{
return RedirectToAction(result);
}
// blah blah
ViewData["message"] = "QN=" + QN + "PN=" + PN + "AC=" + AC;
return this.View("~/Views/PayUp/Pay.aspx");
}
My start URL is http://localhost:3835/SupportingMVCProject/PayUp?QN=ABC-1234567&PN=ABC1234567&AC=123456789. It launches the page just fine and all controls are interactive, all except my "Pay Up!" button (lnkSubmit). Why is lnkSubmit_Click inside Pay.aspx.cs not being invoked?
Your insight is greatly appreciated!
I am pretty sure I have read somewhere that if you use OnClientClick then server side code will not run unless you make some changes
Check out the below link
OnclientClick and OnClick is not working at the same time?

$.get() and $.post() in MVC app works fine in local Cassini webserver but when published into IIS 7.5 it doesn't work anymore

I'm actually stuck on this MVC application and can't find out the cause.
The code works fine in local Vis Studio 2013 Cassini webserver.
Hence when I type the URL in the browser: "/Customer/EnterCustomerDetails"
then I'm displayed a simple form, a DIV tag containing status message "Loading..." and after 5 seconds some data via EF is returned due to the $.get() script that gets executed.
However, when I publish the same code into IIS 7.5 running inside Windows 7 Ultimate, then all I see is the form and only the div tag that displays the message "Loading..." but no data is displayed and it seems the $.get() is not working in the full blown IIS and neither is $.post().
Where am I going wrong? Any help much appreciated. Thanks in advance.
"EnterCustomerDetails.cshtml"
#model P10LearnNewMVCWithEF.ViewModel.CustomerViewModel
#using P10LearnNewMVCWithEF.Models
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>EnterCustomerDetails</title>
#*BELOW Weve IMPORTED the 3 important JQuery LIBRARIES, since we want to use the $.get() AJAX method*#
<script src="~/Scripts/jquery-1.8.3.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
</head>
<body>
<div>
<form id="frm1">
Customer Code:- #Html.TextBoxFor(m => m.Customer.CustomerCode)
#Html.ValidationMessageFor(x => x.Customer.CustomerCode) <br />
Customer Name:- #Html.TextBoxFor(m => m.Customer.CustomerName)
#Html.ValidationMessageFor(x => x.Customer.CustomerName) <br />
<input type="button" value="Submit via true AJAX" id="btn1" onclick="SendData()" />
</form>
<div id="status"></div>
<table id="tbl">
<tr><th>Customer Code</th><th>Customer Name</th></tr>
</table>
<script type="text/javascript">
$("#status").text("Loading..."); //Add STATUS MESSAGE "Loading..." to DIV. Must use ".text" and NOT ".val"
//Making a CALL to the "GetCustomers" ACTION within the "Customer" CONTROLLER and Results returned will be in "BindData"
$.get("GetCustomers", null, BindData);
// The "GetCustomers" ACTION will return the JSON data into this JavaScript function
function BindData(customers) {
var tbl = $("#tbl");
for (var i = 0; i < customers.length; i++) {
var newRow = "<tr>" +
"<td>" + customers[i].CustomerCode + "</td>" +
"<td>" + customers[i].CustomerName + "</td>" +
"</tr>";
tbl.append(newRow);
}
$("#status").text(""); //REMOVING STATUS MESSAGE to EMPTY
}
function SendData() {
$("#status").text("Adding data via ajax..."); //Add STATUS MESSAGE "Loading..." to DIV. Must use ".text" and NOT ".val"
var frm = $("#frm1").serialize();
$.post("Submit", frm, BindData);
$("#Customer_CustomerCode").val("");
$("#Customer_CustomerName").val("");
}
</script>
</div>
</body>
</html>
"CustomerController.cs"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Mvc;
using P10LearnNewMVCWithEF.DAL; //"CustomerDal" in here which derives from "DbContext"
using P10LearnNewMVCWithEF.Models; //"Customer" class in here
using P10LearnNewMVCWithEF.ViewModel;
namespace P10LearnNewMVCWithEF.Controllers
{
public class CustomerController : Controller
{
//Below is our NEW Simplified ACTION that will simply display our Enter Customer Details UI
public ActionResult EnterCustomerDetails()
{
CustomerViewModel objCustomerViewModel = new CustomerViewModel();
objCustomerViewModel.Customer = new Customer(); //This code by SHIV is pretty useless
//NOTE - WE'RE NOT RETRIEVING ANY DATA FROM DATABASE ANYMORE! as we'll do that with "GetCustomers()" ACTION
return View("EnterCustomerDetails", objCustomerViewModel);
}
public ActionResult Submit()
{
Customer obj = new Customer();
obj.CustomerCode = Request.Form["Customer.CustomerCode"]; //"name" is used on Server-side. "id" is used in Client-side.
obj.CustomerName = Request.Form["Customer.CustomerName"];
CustomerDal dal = new CustomerDal();
if (ModelState.IsValid)
{
//Let's INSERT the new Customer into DB via EF
dal.Customers.Add(obj);
dal.SaveChanges();
}
List<Customer> customersColl = dal.Customers.ToList<Customer>(); //Return all data from tCustomer via EF
return Json(customersColl, JsonRequestBehavior.AllowGet); //make sure you say customersColl AND NOT “customersColl”
}
//Below: "GetCustomers()" ACTION will be called by $.get() and simply returns a Collection of JSON data
public ActionResult GetCustomers()
{
CustomerDal dal = new CustomerDal();
List<Customer> customerscoll = dal.Customers.ToList<Customer>();
Thread.Sleep(5000);
return Json(customerscoll, JsonRequestBehavior.AllowGet);
}
}
}
Posting this as an answer so that you can mark it as answered.
That sounds like the identity in your IIS app pool is not authorized for database access. Either assign a new identity that has permission, or grant access to the identity you are using.

MVC dropdown index change

I got a requirement can any one please suggest me ideas if possible with sample
I have a dropdown and beneath i have couple of checkboxes...
For each dropdown item user can select checkboxes.., if user change index of dropdown previous dropdown index and checkbox should maintain in session and new index item can select boxes....
All together we need to post to server...
for eg; dropdown list contains apple,samsung,motorola,htc
checkboxes contain 3G,LTE,Speed,Bandwdth..
once apple is selected he selected values 3g and LTE. and again user selected samsung in dropdown and he selected check boxes speed and lTE.
While posting to server i need to send both list like
apple 3G
apple LTE
Samsung Speed
Samsung LTE
Could any one please suggest some ideas and example
Rather than using Dropdown List you can use div with labels and checkboxes and use jQuery to post data.
You can use jQuery plugin in your case. Here is a good example http://www.erichynds.com/examples/jquery-ui-multiselect-widget/demos/
I am sure there will be many other way to do this, and i think this will help you.
In aspx page:
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" >
<asp:ListItem Value="-1">Select a Device</asp:ListItem>
<asp:ListItem>Apple</asp:ListItem>
<asp:ListItem>Samsung</asp:ListItem>
<asp:ListItem>Nokia</asp:ListItem>
<asp:ListItem>HTC</asp:ListItem>
</asp:DropDownList>
<br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server" RepeatDirection="Horizontal">
<asp:ListItem>3G</asp:ListItem>
<asp:ListItem>LTE</asp:ListItem>
<asp:ListItem>Speed</asp:ListItem>
<asp:ListItem>Bandwidth</asp:ListItem>
</asp:CheckBoxList>
<br />
<asp:Button ID="ButtonSubmit" runat="server" OnClick="ButtonSubmit_Click" Text="Submit" />
<asp:Button ID="ButtonSave" runat="server" OnClick="ButtonSave_Click" Text="Save Data" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Clear First ListBox" />
<br />
<br />
<asp:ListBox ID="ListBox1" runat="server" Height="88px" SelectionMode="Multiple" Width="208px"></asp:ListBox>
<asp:ListBox ID="ListBox2" runat="server" Height="88px" SelectionMode="Multiple" Width="208px"></asp:ListBox>
</div>
</form>
and in code behind file paste this,
protected void Page_Load(object sender, EventArgs e)
{
}
public void LoadDataToListBox(string list1)
{
ListBox1.Items.Add(list1);
}
protected void ButtonSave_Click(object sender, EventArgs e)
{
if (ListBox1.Items.Count != 0)
{
for (int i = 0; i < ListBox1.Items.Count; i++)
{
ListBox2.Items.Add(ListBox1.Items[i]);
}
}
}
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
if(DropDownList1.SelectedValue!="-1")
{
string item1 = "You'r device is " + DropDownList1.SelectedValue;
LoadDataToListBox(item1);
}
foreach (ListItem li in CheckBoxList1.Items)
{
if(li.Selected)
{
LoadDataToListBox("You Choose " + li.Text);
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ListBox1.Items.Clear();
}

Load ASP-MVC View with Ext.Panel loader

I have following layout, related to the one i am describing in this question
<ext:Viewport runat="server">
<Items>
<ext:Panel Region="North" runat="server" ID="TopBar" />
<ext:Panel Region="West" runat="server" ID="Nav" >
<Items>
<ext:Button runat="server" ID="loaderComponentFooBar">
<DirectEvents>
<Click OnEvent="loadFooBar" />
</DirectEvents>
</ext:Button>
//Some more Buttons each with his own loader Function in Code-Behind
</Items>
</ext:Panel>
<ext:Panel runat="server" Region="center" ID="MainPanel" />
</Items>
</ext:Viewport>
on Button-Click i now want to load my View # "/Foo/Bar/" to the MainPanel
How can i achieve this in CodeBehind?
I already tried:
public void loadFooBar(object sender, DirectEventArgs e)
{
MainPanel.Loader.Url = "/Foo/Bar/"; //Throws null reference Exception
MainPanel.Loader.Url = "~/Foo/Bar/"; // same as above
MainPanel.Loader.GetUrlByRoute("Foo/Bar/"); //again the same
MainPanel.Loader.LoadContent("/Foo/Bar/");
//and after each of these attempts except the last went:
MainPanel.Loader.Mode = LoadMode.Frame;
MainPanel.Loader.LoadMask.ShowMask = false;
MainPanel.Loader.LoadContent();
}
Just by the way, i am using aspx-web-application views
I think you should not use a page's code behind for DirectEvents' handlers. It is going out of the MVC concept. You should refer a controller's actions.
Here is an example.
Example View
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<%# Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Ext.Net.MVC v2 Example</title>
</head>
<body>
<ext:ResourceManager runat="server" />
<ext:Viewport runat="server" Layout="BorderLayout">
<Items>
<ext:Panel runat="server" Region="West" Width="100">
<Items>
<ext:Button
runat="server"
Text="Load View 1"
DirectClickUrl=<%# Url.Action("LoadView1") %>
AutoDataBind="true" />
<ext:Button
runat="server"
Text="Load View 2"
DirectClickUrl=<%#Url.Action("LoadView2") %>
AutoDataBind="true" />
</Items>
</ext:Panel>
<ext:Panel ID="MainPanel" runat="server" Region="Center">
<Loader runat="server" Mode="Frame" AutoLoad="false">
<LoadMask ShowMask="true" />
</Loader>
</ext:Panel>
</Items>
</ext:Viewport>
</body>
</html>
Example Controller
using System.Web.Mvc;
using Ext.Net;
using Ext.Net.MVC;
namespace Work2MVC.Controllers
{
public class AspxController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult View1()
{
return View();
}
public ActionResult View2()
{
return View();
}
public ActionResult LoadView1()
{
Panel p = X.GetCmp<Panel>("MainPanel");
p.LoadContent(Url.Action("View1"));
return this.Direct();
}
public ActionResult LoadView2()
{
Panel p = X.GetCmp<Panel>("MainPanel");
p.LoadContent(Url.Action("View2"));
return this.Direct();
}
}
}
Also you can initiate a load request on client side via JavaScript. Then you avoid an additional request.

Convert simple ASP.NET WebForm to MVC

I have simple asp.net page:
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
rptTable.DataSource = GetDataFromDB();
rptTable.DataBind();
}
}
private DataTable GetDataFromDB()
{
DataTable table = new DataTable();
table.Columns.Add("Id", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Rows.Add(1, "HDD");
table.Rows.Add(2, "Video");
table.Rows.Add(3, "RAM");
return table;
}
protected void rptTable_ItemCommand(object source, RepeaterCommandEventArgs e)
{
TextBox tbName = (TextBox)e.Item.FindControl("tbName");
int id = Convert.ToInt32(e.CommandArgument);
string name = tbName.Text;
//Category.Save(int id, string name)
//Rebuild Repeater
}
}
and aspx code:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" EnableEventValidation="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<asp:Repeater ID="rptTable" runat="server" OnItemCommand="rptTable_ItemCommand">
<ItemTemplate>
<tr>
<td>
<%#Eval("id")%>
</td>
<td>
<asp:TextBox ID="tbName" runat="server" Text='<%#Eval("Name")%>'></asp:TextBox>
</td>
<td>
<asp:Button ID="btnSave" runat="server" Text="Save" CommandArgument='<%#Eval("id")%>' />
</td>
</tr>
</ItemTemplate>
</asp:Repeater>
</table>
</div>
</form>
</body>
</html>
It works like simple grid and you are able to edit data directly in the grid.
How can I implement same logic in MVC ?
Thanks!
To replicate the asp:Repeater functionality in an MVC application you would normally use a foreach loop with textboxes within bound to model properties.
You can however if you really want, include an asp:repeater control in an MVC app, but it's not going to work as you'd expect if it relies on postbacks.
If it's a simple read only control, you can put something like the following in your view:
<scipt runat="server">
protected void Page_Load(object sender, EventArgs e) {
rptTable.DataSource = ViewData["yourViewDataList"];
rptTable.DataBind();
}
</script>
This assumes you've got something in the ViewData which can be databound, so to do that you'd likley need to create a controller method to build your DataTable as you've done in 'GetDataFromDB()'
I'm not going to go into the full implementation but at a high level, that's how you could use the control in MVC.

Resources