MVC dropdown index change - asp.net-mvc

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();
}

Related

Nothing happens and no errors binding data from sql server to 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
}

Why am I getting the same Image id from different Image view in a repeater?

I have a repeater that slide shows images from a folder, such that when you click on the current image in the slide, a product page is opened that shows the details information of the selected image.
Meanwhile, I have a productModel that list all the images from the database, such that when you click on any of the images it opens the image product page as above.
Now, my concern is that the hyperlink I attached to the repeater keeps opening the same product page from different image that appears on the repeater. Could anyone please help me point out what I am doing wrong? I will be most grateful!
<ul class="bjqs">
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate><li>
<asp:HyperLink ID="link" runat="server">
<img src='<%# DataBinder.Eval(Container.DataItem,"Value") %>'
title='<%# (DataBinder.Eval(Container.DataItem,"Text").ToString()).Split('.')[0].ToString() %>' alt="">
</asp:HyperLink></li>
</ItemTemplate>
</asp:Repeater>
</ul>
The Server side code:
protected void Page_Load(object sender, EventArgs e)
{
FillPage();
string[] filePaths = Directory.GetFiles(Server.MapPath("~/pages/Management/Images/Products/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
string fileName = Path.GetFileName(filePath);
files.Add(new ListItem(fileName, "/pages/Management/Images/Products/" + fileName));
}
Repeater1.DataSource = files;
Repeater1.DataBind();
}
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
ProductModel productModel = new ProductModel();
List<Product> products = productModel.GetAllProducts();
foreach (Product product in products)
{
Panel productPanel = new Panel();
HyperLink hp = (HyperLink)e.Item.FindControl("link");
hp.NavigateUrl = "~/pages/Product.aspx?id=" + product.ID;
}
}
The reason you have the same Link for every item in your repeater is that when you bind an item to the repeater every single item runs the ItemDataBound event. Inside that event you loop through every Product item and overwrite the HyperLink NavigateURL over and over in the foreach loop until the LAST product in the list is the remaining value for the hyperlink.
If you set a breakpoint and step through the ItemDataBound event you will see this behavior.
I cannot tell you how to fix it because I simply do not see how you intend to map a file to a Product. Once you do that I would suggest bind your repeater to the Product list and add a public property to your Product model which will hold the file location of the image you wish to show. This could then be set in the ItemDataBound event or in the aspx markup as you are doing now with the src for instance.
Some info on the ItemDataBoundEvent including how to get the underlying data item.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.itemdatabound(v=vs.110).aspx
protected void Page_Load(object sender, EventArgs e)
{
FillPage();
if (!IsPostBack)
{
GetData(null, null, null, null);
}
DbRetrival();
}
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
string ID = DataBinder.Eval(e.Item.DataItem, "ID").ToString();
HyperLink hp = (HyperLink)e.Item.FindControl("link");
hp.NavigateUrl = "~/pages/Product.aspx?id=" + ID ;
}
private void DbRetrival()
{
string cs = ConfigurationManager.ConnectionStrings["SuperStoreDBConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(cs);
DataTable dt = new DataTable();
SqlDataAdapter adp = new SqlDataAdapter("Select ID,Image,Name from Product",con );
adp.Fill(dt);
Repeater1.DataSource = dt;
Repeater1.DataBind();
}
private void FolderRetrival()
{
string[] filePaths = Directory.GetFiles(Server.MapPath("~/pages/Management/Images/Products/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
string fileName = Path.GetFileName(filePath);
files.Add(new ListItem(fileName, "/pages/Management/Images/Products/" + fileName));
}
Repeater1.DataSource = files;
Repeater1.DataBind();
}
The asp page:
<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
<ItemTemplate>
<li>
<asp:HyperLink ID="link" runat="server">
<br /> <asp:Image runat="server" ImageUrl='<%#"~/pages/Management/Images/Products/" + String.Format("{0}",
Eval("Image")) %>' Width='180px' Height='145px' /> </Image>
<br /> <%# Eval("Name")%>
</asp:HyperLink>
</li>
</ItemTemplate>

SqlDataSource custom paging

I need use sqldatasource(stored proc) to bind a gridview.
<asp:GridView ID="gvBC" runat="server" AutoGenerateColumns="False" ShowFooter="True" AllowSorting="True" AllowPaging="True" pageSize ="3" DataSourceID="dsBCSearch">
<Columns>
<asp:BoundField DataField="ContactID" HeaderText="ContactID" Visible="false"/>
<asp:BoundField DataField="BldgNum" HeaderText="Bldg#" SortExpression="BldgNum" />
</Columns>
<EmptyDataTemplate> No Building Coordinator Found. </EmptyDataTemplate>
<EmptyDataRowStyle HorizontalAlign="Center" />
</asp:GridView>
<asp:SqlDataSource ID="dsBCSearch" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnStr %>" SelectCommand="GetBC" SelectCommandType="StoredProcedure"
SortParameterName="SortExpression" />
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
LoadBC();
}
protected void LoadBC()
{
dsBCSearch.SelectCommand = "GetBCwP";
dsBCSearch.SelectParameters.Clear();
dsBCSearch.SelectParameters.Add("LName", this.txtLNAme.Text.Trim());
dsBCSearch.SelectParameters.Add("Active", this.chkActive.Checked.ToString());
//dsBCSearch.SelectParameters.Add("sortExpression", this.gvBC.SortExpression);
dsBCSearch.SelectParameters.Add("startRowIndex", this.gvBC.PageIndex.ToString());
dsBCSearch.SelectParameters.Add("maximumRows", this.gvBC.PageSize.ToString());
this.gvBC.DataBind();
}
Now just render first page (3 records) and in footer no number showing up. HOw can I add paging to footer?
Thanks
sqldatasource is not good for custom paging. I have to add another pager part and like old asp page, to manually write the code.
But objectdatasource is much easy for this. It will have some parameter like StartRowIndexParameterName MaximumRowsParameterName SortParameterName SelectCountMethod. It will auto pass to data souce

CalendarExtender loose his value on postback

Here is the code of my date selecting control.
When the page containing the control is submitted AFTER the Page_Load and link button click events passed, tb is reset to it is initial value (which is today)
<div class="ui-form-text">
<div>
<asp:TextBox ID="tb" runat="server" autocomplete="off"></asp:TextBox></div>
</div>
<ajaxToolkit:CalendarExtender ID="ce" runat="server" TargetControlID="tb" Format="dd/MM/yyyy"
CssClass="calendar" EnableViewState="true">
</ajaxToolkit:CalendarExtender>
<ajaxToolkit:MaskedEditExtender ID="mee" runat="server" TargetControlID="tb" Enabled="true"
Mask="99\/99\/9999" ClearMaskOnLostFocus="false" EnableViewState="true">
</ajaxToolkit:MaskedEditExtender>
<asp:CompareValidator ID="cv" runat="server" ControlToValidate="tb" Display="Dynamic"
ErrorMessage="Невалидна дата" Operator="DataTypeCheck" Type="Date" ForeColor="Red">
</asp:CompareValidator>
<asp:RangeValidator ID="rv" runat="server" ControlToValidate="tb" Type="Date">
</asp:RangeValidator>
I am having the same problem myself and the only solution (well, workaround) I could find was this:
ASP.NET Ajax CalendarExtender will not update SelectedDate value
I hope this can help you, this worked for me.
String tmp_;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (Request[txtCalendarExtender.UniqueID] != null)
{
if (Request[txtCalendarExtender.UniqueID].Length > 0)
{
this.tmp_ = Request[txtCalendarExtender.UniqueID];
}
}
}
}

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