How to display database values in div - c#

I am trying to get values from database and display it in a div.
here I am getting values from mysql database and I have HTML in .aspx page. I have 20 records and I want to print the data in different divs.
how can I do it using for loop.
HTML:
<div class="col-xs-12 col-sm-5 col-md-5 col-lg-3">
<div class="panel panel-warning">
<div class="panel-heading">Animal Name here</div>
<div class="panel-body">Animal image</div>
</div>
</div>
C#:
protected void Page_Load(object sender, EventArgs e)
{
try
{
string scon = "SERVER=localhost;DATABASE=animal_adoption_site;UID=root;";
MySqlConnection con = new MySqlConnection(scon);
String s = "select animal_pet_name,animal_donation_plan,animal_image_uploaded from animal_details";
MySqlDataAdapter dat = new MySqlDataAdapter(s, con);
}
catch (Exception ex)
{
string s = ex.ToString();
Response.Write(s);
}
}

You can do something like
Imagine in the server you have the following
public List<string> MyItems { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
MyItems = new List<string>();
MyItems.Add("Item 1");
MyItems.Add("Item 2");
MyItems.Add("Item 3");
MyItems.Add("Item 4");
}
In the client you can do a for loop for the items
<% foreach (string myItem in MyItems)
{ %>
<div class="col-xs-12 col-sm-5 col-md-5 col-lg-3">
<div class="panel panel-warning">
<div class="panel-heading"><%: myItem %></div>
<div class="panel-body">Animal image</div>
</div>
</div>
<%} %>

Related

Blazor List Refresh After Update

This post is entirely updated to put all code in one class and to try to make it as straight-forward as possible.
The project works perfectly EXCEPT for one thing: When a student record is updated, the database is updated, but the visible list does not update.
The only way I've been able to see the changes is when I refresh the entire page (see NavigationManager line at bottom of code).
Can you please help me understand what I'm not doing right here.
#page "/Students2";
#using ParentChild.Models;
#inject IJSRuntime JS; // Used for Confirmation Dialog & Alert Box
#inject NavigationManager NavigationManager // Used to Refresh Entire Page
<h3>Students 2</h3>
#if (byStudents == null)
{
<p><em>Loading...</em></p>
}
else if (!byStudents.Any())
{
<p><em>No students in database. Please add some.</em></p>
}
else
{
<table class="table">
<thead>
<tr>
<th>First</th>
<th>Last</th>
<th>Street</th>
<th>City</th>
<th>State</th>
<th>Zip</th>
<th>Cell</th>
<th>Home</th>
<th>Email</th>
<th>Note</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var byStudent in byStudents)
{
<tr>
<td>#byStudent.SFirst</td>
<td>#byStudent.SLast</td>
<td>#byStudent.SStreet</td>
<td>#byStudent.SCity</td>
<td>#byStudent.SState</td>
<td>#byStudent.SZip</td>
<td>#byStudent.SCell</td>
<td>#byStudent.SHome</td>
<td>#byStudent.SEmail</td>
<td>#byStudent.SNote</td>
<td>
<input type="button" class="btn btn-primary" #onclick="#(() => OpenEditStudent(#byStudent.SId))" value="Edit" />
<nbsp></nbsp>
<input type="button" class="btn btn-danger" #onclick="#(async () => await DeleteStudentAction(#byStudent.SId))" value="Delete" />
</td>
</tr>
}
</tbody>
</table>
}
<button class="btn btn-primary" #onclick="() => OpenAddStudent()">Add New Student</button>
#if (showBackdrop)
{
<div class="modal-backdrop fade show"></div>
}
<!-- Define Modal Pop-UP in this Page -->
<div class="modal #modalClass" tabindex="-1" role="dialog" style="display:#modalDisplay; overflow-y: auto;">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
<!-- Pop-Up Title Section -->
#{
var txt = "";
if ((SId == null) | (SId == ""))
{
txt = "Add Student";
#txt;
}
else
{
txt = "Edit Student";
#txt;
}
}
</h5>
<!-- Pop-Up Close Button at Top -->
<button type="button" class="close" data-dismiss="modal" aria-label="Close" #onclick="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<!-- Pop-Up Body Section -->
<div class="form-group row">
<input id="SId" #bind="SId" type="hidden" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SFirst" class="col-sm-8 col-form-label">First Name:</label>
<input id="SFirst" #bind="SFirst" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SLast" class="col-sm-8 col-form-label">Last Name:</label>
<input id="SLast" #bind="SLast" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SStreet" class="col-sm-8 col-form-label">Street:</label>
<input id="#SStreet" #bind="SStreet" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SCity" class="col-sm-8 col-form-label">City:</label>
<input id="#SCity" #bind="SCity" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SState" class="col-sm-8 col-form-label">State:</label>
<input id="#SState" #bind="SState" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SZip" class="col-sm-8 col-form-label">Zip:</label>
<input id="#SZip" #bind="SZip" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SCell" class="col-sm-8 col-form-label">Cell #:</label>
<input id="#SCell" #bind="SCell" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SHome" class="col-sm-8 col-form-label">Home #:</label>
<input id="#SHome" #bind="SHome" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SEmail" class="col-sm-8 col-form-label">Email:</label>
<input id="#SEmail" #bind="SEmail" class="col-sm-4 form-control" />
</div>
<div class="form-group row">
<label for="#SNote" class="col-sm-8 col-form-label">Note:</label>
<input id="#SNote" #bind="SNote" class="col-sm-4 form-control" />
</div>
</div>
<div class="modal-footer">
<!-- Pop-Up Body Section -->
#{
if ((SId == null) | (SId == ""))
{
<button type="button" class="btn btn-primary" #onclick="async () => await AddStudentAction()">Add</button>
}
else
{
<button type="button" class="btn btn-primary" #onclick="async () => await UpdateStudentAction(this.SId)">Update</button>
}
}
<button type="button" class="btn btn-secondary" data-dismiss="modal" #onclick="() => this.Close()">Close</button>
</div>
</div>
</div>
</div>
#code {
//-------------------------------------------------------------------------
// Modal Control Variables and Code
//-------------------------------------------------------------------------
private string modalDisplay = "none;";
private string modalClass = "";
private bool showBackdrop = false;
//--- Open Modal...
public void Open()
{
modalDisplay = "block;";
modalClass = "show";
showBackdrop = true;
}
//--- Close Modal...
public void Close()
{
modalDisplay = "none";
modalClass = "";
showBackdrop = false;
}
//-------------------------------------------------------------------------
// Student List from Database
//-------------------------------------------------------------------------
DB_136837_byogaContext db = new DB_136837_byogaContext();
private List<ByStudents> byStudents;
//--- Build Student List on Page Initialization...
protected override void OnInitialized()
{
byStudents = db.ByStudents.ToList();
}
//-------------------------------------------------------------------------
// Modal Parameters
//-------------------------------------------------------------------------
private Modal modal { get; set; }
[Parameter]
public string SId { get; set; } = "";
[Parameter]
public string SFirst { get; set; } = "";
[Parameter]
public string SLast { get; set; } = "";
[Parameter]
public string SStreet { get; set; } = "";
[Parameter]
public string SCity { get; set; } = "";
[Parameter]
public string SState { get; set; } = "";
[Parameter]
public string SZip { get; set; } = "";
[Parameter]
public string SCell { get; set; } = "";
[Parameter]
public string SHome { get; set; } = "";
[Parameter]
public string SEmail { get; set; } = "";
[Parameter]
public string SNote { get; set; } = "";
//-------------------------------------------------------------------------
// Open Modal to Add Student
//-------------------------------------------------------------------------
protected void OpenAddStudent()
{
//-- Clear Any Info Set in Previous Edit Requests...
SId = "";
SFirst = "";
SLast = "";
SStreet = "";
SCity = "";
SState = "";
SZip = "";
SCell = "";
SHome = "";
SEmail = "";
SNote = "";
//--- Open Modal Popup...
this.Open();
}
//-------------------------------------------------------------------------
// Open Modal to Edit Student
//-------------------------------------------------------------------------
protected void OpenEditStudent(int myID)
{
//--- Build & Run SQL Select Statement...
using (var myContext = new DB_136837_byogaContext())
{
//--- Grab Info for Selected Student...
var myQuery = (from s in myContext.ByStudents where s.SId == myID select s).Single();
//--- Set Fields on Popup Form...
this.SId = myQuery.SId.ToString();
this.SFirst = myQuery.SFirst;
this.SLast = myQuery.SLast;
this.SStreet = myQuery.SStreet;
this.SCity = myQuery.SCity;
this.SState = myQuery.SState;
this.SZip = myQuery.SZip;
this.SCell = myQuery.SCell;
this.SHome = myQuery.SHome;
this.SEmail = myQuery.SEmail;
this.SNote = myQuery.SNote;
}
//--- Open Modal Form...
this.Open();
}
//-------------------------------------------------------------------------
// Delete Selected Student from Database with Confirmation Dialog
//-------------------------------------------------------------------------
protected async Task DeleteStudentAction(int myID)
{
bool isConfirmed = await JS.InvokeAsync<bool>("confirm", $"Do you sure you want to permanently delete whis record?");
if (isConfirmed)
{
//--- Build & Run SQL Delete Statement...
using (var myContext = new DB_136837_byogaContext())
{
var myQuery = (from d in myContext.ByStudents where d.SId == myID select d).Single();
myContext.ByStudents.Remove(myQuery);
myContext.SaveChanges();
}
//--- Delete Complete Dialog...
await JS.InvokeVoidAsync("alert", "Record Deleted");
//--- Refresh Page...
await InvokeAsync(() =>
{
StateHasChanged();
this.OnInitialized();
});
}
}
//-------------------------------------------------------------------------
// Add Student to Database
//-------------------------------------------------------------------------
protected async Task AddStudentAction()
{
//--- Define the New Student...
var newStudent = new ByStudents();
newStudent.SFirst = SFirst;
newStudent.SLast = SLast;
newStudent.SStreet = SStreet;
newStudent.SCity = SCity;
newStudent.SState = SState;
newStudent.SZip = SZip;
newStudent.SCell = SCell;
newStudent.SHome = SHome;
newStudent.SEmail = SEmail;
newStudent.SNote = SNote;
//--- Add New Student to Database...
using (var myContext = new DB_136837_byogaContext())
{
myContext.ByStudents.Add(newStudent);
myContext.SaveChanges();
}
//--- Close the Popup...
this.Close();
//--- Refresh Page...
await InvokeAsync(() =>
{
StateHasChanged();
this.OnInitialized();
});
}
//-------------------------------------------------------------------------
// Update Student in Database
//-------------------------------------------------------------------------
protected async Task UpdateStudentAction(string myID)
{
//--- Build & Run SQL Select Statement...
using (var myContext = new DB_136837_byogaContext())
{
//--- Update Info for Selected Student...
var myQuery = (from d in myContext.ByStudents where d.SId == Convert.ToInt32(myID) select d).Single();
myQuery.SFirst = this.SFirst;
myQuery.SLast = this.SLast;
myQuery.SStreet = this.SStreet;
myQuery.SCity = this.SCity;
myQuery.SState = this.SState;
myQuery.SZip = this.SZip;
myQuery.SCell = this.SCell;
myQuery.SHome = this.SHome;
myQuery.SEmail = this.SEmail;
myQuery.SNote = this.SNote;
myContext.ByStudents.Update(myQuery);
myContext.SaveChanges();
}
//--- Close the Popup...
this.Close();
//--- Refresh Page...
await InvokeAsync(() =>
{
StateHasChanged();
this.OnInitialized();
});
//--- Refresh Page by Reloading...SHOULD NOT HAVE TO DO THIS!
//NavigationManager.NavigateTo("Refresh/Students2");
}
}
Any and all help is appreciated. Thanks!
On your add/update page, after you are done with your operation and you are navigating back to your list, add the 'true' parameter to force a reload of the list page.
NavigationManager.NavigateTo("students", true);
See this link
If I understand correctly, you have a child component modal that handles the crud responsible for data displayed by a parent component.
I believe if you call StateHasChanged() from a child component the state is updated in the child component's scope unless the parent is notified its state should be updated. I would try adding an eventcallback from your child component modal to the parent that triggers a StateHasChanged() on the parent level. You could manually invoke the callback on any child crud methods after the work is done.
Something similar to this: Blazor - Execute a parent component's method when a child component onclick event occurs

MVC modal popup from partial view - not working

I'm developing an MVC webpage, where I'm intending to do Create and Edit operations via a pop-up. So, the idea is I click on the 'Create' button, a modal-popup appears with all the model fields empty and allows user to input. In the same way, when user double clicks on any row, the row would open up for edit via the same pop-up, this time with the details filled from that row.
So, for reusage, I have decided to develop a single partial view(that would be the pop-up) and accept 'Model' as input.
My problem is, no matter what I do, I'm not able to make the partial view come up as pop-up. (Note: my main parent Index view would accpet input as List
Here is my code:
MY Index view:
#model List<TrackBuildConfig.DAL.Models.BuildModel>
#{
Layout = null;
}
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/MyScript.js" type="text/javascript"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="jumbotron">
<h1>Track Coverity and Nightly builds</h1>
<h4>on your own!</h4>
</div>
<div class="container-fluid">
<div class="row btn-group">
#Html.ActionLink("Create a new record", "SaveData", "Home", new { configID = 0 }, new { #class = "btn btn-primary modal-link", id = "btnCreate"})
</div>
<div class="modal fade" aria-labelledby="ModalLabel" id="modal-container" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content" style="width: 500px !important; margin:10px !important">
</div>
</div>
</div>
</div>
</body>
</html>
Script:
$(function () {
$('body').on('click', '.modal-link', function (e) {
e.preventDefault();
$('#btnCreate').attr('data-toggle', 'modal');
$('#btnCreate').attr('data-target', '#modal-container');
$('#modal-container').modal('show');
return true;
});
}
});
Partial view _PartialModal.csHtml
#model TrackBuildConfig.DAL.Models.BuildModel
#{
Layout = null;
}
<html>
<head>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/MyScript.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="">
<div class="modal-header">
<button type="button" class="close" aria-hidden="true" data-dismiss="modal">&times</button>
<h4>Configure Coverity and Nightly builds</h4>
</div>
<div class="modal-body" style="height: 400px;">
#using (Html.BeginForm("SaveData", "Home", FormMethod.Post))
{
<div class="row">
<div class="form-group row">
<div class="col-sm-4">
#Html.Label("Stream name", new { #class = "control-label" })
</div>
<div class="col-sm-6">
#Html.DropDownList("BuildLocations", (IEnumerable<SelectListItem>)ViewBag.BuildLocations, new { #class = "col-sm-6 form-control", id = "ddlBuildLocation" })
</div>
</div>
<div class="form-group row">
<div class="col-sm-4">
#Html.Label("Build Location", new { #class = "control-label" })
</div>
<div class="col-sm-6">
#Html.DropDownList("Streams", (IEnumerable<SelectListItem>)ViewBag.Streams, new { #class = "col-sm-6 form-control", id = "ddlStreams" })
</div>
</div>
<div class="form-group row">
<div class="col-sm-4">
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.IsCoverity)
Enable Coverity
</label>
</div>
</div>
<div class="col-sm-8">
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.IsNightly)
Enable Nightly build
</label>
</div>
</div>
<label style="color: red; font-weight: 300;" id="warningEnableBuild"></label>
</div>
<div class="form-group row">
#Html.Label("Email for Coverity", new { #class = "col-sm-4 control-label" })
<div class="col-sm-8" style="width: 100%">
#Html.TextAreaFor(m => m.EmailCoverity, new { #class = "form-control clsEmailCoverity", #placeholder = "Enter some value", #onkeyup = "return true;", #rows = "5", id = "txtEmailCoverity" })
#*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*#
<span class="help-block">Please add only comma separated addresses!</span>
<label style="color: red; font-weight: 300;" id="warningLabelCoverity"></label>
</div>
</div>
<div class="form-group row">
#Html.Label("Email for Nightly", new { #class = "col-sm-4 control-label" })
<div class="col-sm-8" style="width: 100%">
#Html.TextAreaFor(m => m.EmailNightly, new { #class = "form-control clsEmailNightly", #placeholder = "Enter some value", #onkeyup = "return true;", #rows = "5", id = "txtEmailNightly" })
#*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*#
<span class="help-block">Please add only comma separated addresses!</span>
<label style="color: red; font-weight: 300;" id="warningLabelNightly"></label>
</div>
</div>
<div class="modal-footer">
<button id="btnSave" class="btn btn-success" type="submit" role="button">Save changes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
}
</div>
</div>
</body>
</html>
Controller methods:
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
GetData getdata = new GetData();
return View(getdata.GetDataFromTable());
}
[HttpPost]
public ActionResult SaveData()
{
return View("Index");
}
//[HttpGet]
public ActionResult SaveData(int configID)
{
BuildModel model = new BuildModel();
PopulateBuildLocations();
PopulateStreams();
//Create
if (configID != 0)
{
GetData getdata = new GetData();
model = getdata.GetDataFromTable().Where(co => co.ConfigID == configID).FirstOrDefault();
}
else
{
model.BuildLocation = "";
model.EmailCoverity = "";
model.EmailNightly = "";
model.IsCoverity = false;
model.IsNightly = false;
}
return PartialView("_PartialModal", model);
}
public void PopulateBuildLocations()
{
string reportTypes = ConfigurationManager.AppSettings["ddlStreams"].ToString();
ViewBag.BuildLocations = reportTypes.Split('|')
.Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
}
public void PopulateStreams()
{
List<string> lstStreams = new List<string>();
for (int i = 0; i < 6; i++)
{
lstStreams.Add("Stream " + i);
}
ViewBag.Streams = lstStreams.Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
}
}
This is the link I used as reference. Reference
Please put my code in your visual studio and see that it works.
Controller/View Model/Classes:
public class BuildModel
{
public string theBuildModel { get; set; }
public int ConfigID { get; set; }
public string BuildLocation { get; set; }
public string EmailCoverity { get; set; }
public string EmailNightly { get; set; }
public bool IsCoverity { get; set; }
public bool IsNightly { get; set; }
}
public class GetData
{
public IList<BuildModel> GetDataFromTable()
{
IList<BuildModel> list = new List<BuildModel>();
var buildModel1 = new BuildModel { theBuildModel = "one" };
var buildModel2 = new BuildModel { theBuildModel = "two" };
var buildModel3 = new BuildModel { theBuildModel = "three" };
list.Add(buildModel1);
list.Add(buildModel2);
list.Add(buildModel3);
return list;
}
}
public class HomeController : Controller
{
[HttpPost]
public ViewResult SaveData(BuildModel buildModel)
{
GetData getdata = new GetData();
var model = getdata.GetDataFromTable();
return View("IndexStackOverflow", model);
}
[HttpGet]
public PartialViewResult SaveData(int configID)
{
BuildModel model = new BuildModel();
PopulateBuildLocations();
PopulateStreams();
//Create
if (configID != 0)
{
GetData getdata = new GetData();
model = getdata.GetDataFromTable().Where(co => co.ConfigID == configID).FirstOrDefault();
}
else
{
model.BuildLocation = "";
model.EmailCoverity = "";
model.EmailNightly = "";
model.IsCoverity = false;
model.IsNightly = false;
}
return PartialView("_PartialModal", model);
}
public void PopulateBuildLocations()
{
string reportTypes = ConfigurationManager.AppSettings["ddlStreams"].ToString();
ViewBag.BuildLocations = reportTypes.Split('|')
.Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
}
public void PopulateStreams()
{
List<string> lstStreams = new List<string>();
for (int i = 0; i < 6; i++)
{
lstStreams.Add("Stream " + i);
}
ViewBag.Streams = lstStreams.Select((text, value) => new SelectListItem { Text = text, Value = value.ToString() });
}
public ActionResult IndexStackOverflow()
{
GetData getdata = new GetData();
return View(getdata.GetDataFromTable());
}
web.config:
<appSettings>
<add key="ddlStreams" value="text1|value1"/>
</appSettings>
View:
#model List<Testy20161006.Controllers.BuildModel>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexStackOverflow</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
#*YOU MUST PUT THE NEXT LINE FOLLOWING IN YOUR CODE-NUGET IF YOU NEED TO GET THE SCRIPT*#
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
<div class="jumbotron">
<h1>This is part of the Main Page</h1>
<h1>Partial View rendered in result</h1>
<h1>Track Coverity and Nightly builds</h1>
<h4>on your own!</h4>
</div>
<div class="container-fluid">
<div class="row btn-group">
#*#Html.ActionLink("Create a new record", "SaveData", "Home", new { configID = 0 },
new { #class = "btn btn-primary modal-link", id = "btnCreate" })*#
#using (Ajax.BeginForm("SaveData", "Home", new { configID = 0 },
new AjaxOptions
{
UpdateTargetId = "result",
InsertionMode = InsertionMode.Replace,
OnFailure = "error",
HttpMethod = "Get"
}))
{
<input id="btnCreate" type="submit" value="Create a new record" class="btn btn-primary modal-link" />
}
<div id="result"></div>
</div>
</div>
</body>
</html>
Partial View in shared folder:
#model Testy20161006.Controllers.BuildModel
<script type="text/javascript">
$(function () {
$('#myModal').modal('show');
})
</script>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Configure Coverity and Nightly builds</h4>
</div>
<div class="modal-body">
<div class="modal-body" style="height: 400px;">
#using (Html.BeginForm("SaveData", "Home", FormMethod.Post))
{
<div class="row">
<div class="form-group row">
<div class="col-sm-4">
#Html.Label("Stream name", new { #class = "control-label" })
</div>
<div class="col-sm-6">
#Html.DropDownList("BuildLocations", (IEnumerable<SelectListItem>)ViewBag.BuildLocations, new { #class = "col-sm-6 form-control", id = "ddlBuildLocation" })
</div>
</div>
<div class="form-group row">
<div class="col-sm-4">
#Html.Label("Build Location", new { #class = "control-label" })
</div>
<div class="col-sm-6">
#Html.DropDownList("Streams", (IEnumerable<SelectListItem>)ViewBag.Streams, new { #class = "col-sm-6 form-control", id = "ddlStreams" })
</div>
</div>
<div class="form-group row">
<div class="col-sm-4">
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.IsCoverity)
Enable Coverity
</label>
</div>
</div>
<div class="col-sm-8">
<div class="checkbox">
<label>
#Html.CheckBoxFor(m => m.IsNightly)
Enable Nightly build
</label>
</div>
</div>
<label style="color: red; font-weight: 300;" id="warningEnableBuild"></label>
</div>
<div class="form-group row">
#Html.Label("Email for Coverity", new { #class = "col-sm-4 control-label" })
<div class="col-sm-8" style="width: 100%">
#Html.TextAreaFor(m => m.EmailCoverity, new { #class = "form-control clsEmailCoverity", #placeholder = "Enter some value", #onkeyup = "return true;", #rows = "5", id = "txtEmailCoverity" })
#*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*#
<span class="help-block">Please add only comma separated addresses!</span>
<label style="color: red; font-weight: 300;" id="warningLabelCoverity"></label>
</div>
</div>
<div class="form-group row">
#Html.Label("Email for Nightly", new { #class = "col-sm-4 control-label" })
<div class="col-sm-8" style="width: 100%">
#Html.TextAreaFor(m => m.EmailNightly, new { #class = "form-control clsEmailNightly", #placeholder = "Enter some value", #onkeyup = "return true;", #rows = "5", id = "txtEmailNightly" })
#*<textarea id="txtEmailCoverity" class="form-control clsEmailCoverity" runat="server" rows="5" placeholder="Enter email IDs for Coverity builds" onkeyup="SetEmailForNightly()"></textarea>*#
<span class="help-block">Please add only comma separated addresses!</span>
<label style="color: red; font-weight: 300;" id="warningLabelNightly"></label>
</div>
</div>
<div class="modal-footer">
<button id="btnSave" class="btn btn-success" type="submit" role="button">Save changes</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
}
</div>
</div>
</div>
</div>
</div>

Use Hyperlink in code

how can i use a asp:hyperlink in my code where the user can press the number and go to another page, so this is my code,
if (dt != null)
{
foreach (DataRow dr in dt.Rows)
{
loggedin.Text = "Registered users today: " + dr["RegisteredUsersToday"];
}
if (dtParent != null)
{
foreach (DataRow dr in dtParent.Rows)
{
loggedinParents.Text = "Registered Parents today: " + dr["RegisteredUsersToday"];
}
}
else
{
loggedinParents.Text = "Registered Parents today: 0 ";
}
if (dtTeacher != null)
{
foreach (DataRow dr in dtTeacher.Rows)
{
loggedinTeachers.Text = "Registered Teachers today: " + dr["RegisteredUsersToday"];
}
}
else
{
loggedinTeachers.Text = "Registered Teachers today: 0 ";
}
if (dtStudents != null)
{
foreach (DataRow dr in dtStudents.Rows)
{
loggedinStudents.Text = "Registered Students today: " + dr["RegisteredUsersToday"];
}
}
else
{
loggedinStudents.Text = "Registered Students today: 0 ";
}
}
else
{
loggedin.Text = "No new users today";
}
i want the hyperlink to be between RegisteredUsersToday, and this is my html where a have created the labels,
<div class="panel panel-default">
<div class="text-center panel-heading">
<a data-toggle="collapse" href="#collapse1" >
<asp:Label runat="server" ID="loggedin"></asp:Label>
</a>
</div>
<br />
<div id="collapse1" class="panel-collapse collapse">
<div class="text-center">
<asp:Label runat="server" ID="loggedinParents"></asp:Label>
</div>
<br />
<div class="text-center">
<asp:Label runat="server" ID="loggedinTeachers"></asp:Label>
</div>
<br />
<div class="text-center">
<asp:Label runat="server" ID="loggedinStudents"></asp:Label>
</div>
</div>
</div>

Display a header for each grouping of items in a repeater?

I have an product order review page that displays a list of whatever the user has entered. What is needed is the name of the location that each product or product grouping belongs to (i.e. If the user selected 3 products from under the "Desks" listing, those three products should appear under the header "Desks" on the order review page. If the user purchased 5 items from under the "Lobbies" listing, then those 5 products should appear under the header "Lobbies" on the order review page).
Currently, I can get the correct header text, but the text repeats itself with each item (i.e. The header "Desks" appears above each of the 3 items ordered under the "Desks" listing). I would like it to appear only once per item/grouping of items but I am not sure how to do it.
I am using a repeater to display the order information to the user, and everything else is working the way I want it. It's just this little bit I'm confused about. Any help would be great. Thanks in advance!
Here is the designer code:
<asp:Repeater ID="orderRepeater" runat="server" >
<itemtemplate>
<h3 class="locationName"><%# Eval("LocationName") %></h3>
<div class="headerRow">
<div class="header">
<div class="thumb"><p></p></div>
<div class="headerField name"><p class="hField">Product</p></div>
<div class="headerField sku"><p class="hField">GOJO SKU</p></div>
<div class="headerField size"><p class="hField">Size</p></div>
<div class="headerField case"><p class="hField">Case Pack</p></div>
<div class="headerField qty"><p class="hField">Quantity</p></div>
</div>
</div>
<div class="table">
<div class="row">
<div class="thumb"><%# Eval("Thumbnail") %></div>
<div class="field name"><p class="pField"> <%#Eval("ProductName") %> </p></div>
<div class="field sku"><p class="pField"> <%#Eval("Sku") %></p></div>
<div class="field size"><p class="pField"> <%#Eval("Size") %></p></div>
<div class="field case"><p class="pField"><%#Eval("CasePack") %></p></div>
<div class="field qty"><p class="pField"><%#Eval("Qty") %></p></div>
</div>
</div>
</itemtemplate>
</asp:Repeater>
Here is the code behind:
private void Page_Load(object sender, EventArgs e)
{
Label lbl = (Label)FindControl("orderLbl");
Item CurrentItem = Sitecore.Context.Item;
Item HomeItem = ScHelper.FindAncestor(CurrentItem, "gojoMarket");
if (Session["orderComplete"] != null && Session["orderComplete"] != "")
{
if (HomeItem != null)
{
Item ProductGroup = HomeItem.Axes.SelectSingleItem(#"child::*[##templatename='gojoMarketOfficeBuildigProductMap']/*[##templatename='gojoOrderReview']");
Database db = Sitecore.Context.Database;
DataSet dset = new DataSet();
if (ProductGroup != null)
{
string InFromSession = Session["orderComplete"].ToString();
try
{
DataTable summary = dset.Tables.Add("summary");
summary.Columns.Add("LocationName", Type.GetType("System.String"));
summary.Columns.Add("Thumbnail", Type.GetType("System.String"));
summary.Columns.Add("ProductName", Type.GetType("System.String"));
summary.Columns.Add("Sku", Type.GetType("System.String"));
summary.Columns.Add("Size", Type.GetType("System.String"));
summary.Columns.Add("CasePack", Type.GetType("System.String"));
summary.Columns.Add("Qty", Type.GetType("System.String"));
summary.Columns.Add("Location", Type.GetType("System.String"));
Label qL = (Label)FindControl("qty");
string[] orders = InFromSession.Split(';');
foreach (string order in orders)
{
int total = orders.GetUpperBound(0);
if (order != "")
{
string[] infos = order.Split(',');
string ids = infos.GetValue(0).ToString();
string qtys = infos.GetValue(1).ToString();
if (ids != "")
{
Item CatalogueItem = db.Items[ids];
DataRow drow = summary.NewRow();
Item LocationItem = ScHelper.FindAncestor(CatalogueItem, "gojoProductLocation");
if (LocationItem != null)
{
//this returns the header text values that I need
string LocationName = LocationItem.Fields["Header"].ToString();
drow["LocationName"] = LocationName;
}
Item orderItem = db.Items[CatalogueItem.Fields["Reference SKU"].Value];
if (orderItem != null)
{
Item marketItem = db.Items[orderItem.Fields["Master Product"].Value];
if (marketItem != null)
{
Item CPNItem = db.Items[marketItem.Fields["Complete Product Name"].Value];
drow["Thumbnail"] = "";
Sitecore.Data.Fields.XmlField fileField = marketItem.Fields["Thumbnail"];
drow["Thumbnail"] = "<image src=\"" + ScHelper.GetCorrectFilePath(fileField) + "\" border=\"0\" alt=\"\">";
if (CPNItem != null)
{
var name = CPNItem["Complete Name"];
drow["ProductName"] = name;
}
drow["Sku"] = marketItem.Fields["SKU"].Value;
drow["CasePack"] = marketItem.Fields["Case Pack"].Value;
if (marketItem.Fields["Size"] != null)
{
drow["Size"] = marketItem.Fields["Size"].Value;
}
else
{
drow["Size"] = "N/A";
}
drow["Qty"] = qtys.ToString();
summary.Rows.Add(drow);
}
}
}
}
}
orderRepeater.DataSource = dset;
orderRepeater.DataMember = "summary";
orderRepeater.DataBind();
}
catch (Exception x)
{
Response.Write(x.Message.ToString());
}
}
}
}
else
{
HyperLink none = (HyperLink)FindControl("link");
Label msg = (Label)FindControl("msgLbl");
none.Visible = true;
msg.Text = "You have not selected any items for purchase. To purchase items, please visit our complete product listing: ";
}
}
I'd put the header in the <HeaderTemplate>. So it'd look like:
<asp:Repeater ID="orderRepeater" runat="server" >
<HeaderTemplate><h3><asp:Literal runat="server" id="header" /></h3></HeaderTemplate>
<ItemTemplate>[your existing code here]</ItemTemplate>
</asp:Repeater>
And in code behind do something like:
protected void orderRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Header)
{
((Literal)e.Item.FindControl("header")).Text = "The header" // Whatever you would like this to be;
}
}

Databinding custom objects to controls in aspx file and not code behind

I'm having issues fully binding a generic list in aspx file. Although It binds to my <p> and <h> tags properly but not my ImageButton. I'm I doing something wrong here. Below is my code
Aspx File
<%
int count = 1;
for (item = 0; item < mList.Count; AddItem())
{
if (count == 3)
{ %>
<div class="one_third_last">
<% count = 0;
}
else
{ %>
<div class="one_third">
<%}
count++;%>
<div class="modern_img_frame modern_four_col_large">
<div class="preload_four_col_large">
<div class="attachment-fadeIn">
<asp:ImageButton ID="ImageButton" runat="server" ImageUrl="~/images2/premium-website-template-2.jpg"
ToolTip="CSS Template" AlternateText="CSS Template" Width="190" Height="111"
CommandName="<%# mList[item].PaymentCode %>" CommandArgument="<%# mList[item].PaymentDescription %>"
OnCommand="ImageButton_Command" />
</div>
</div>
</div>
<!-- end modern_img_frame -->
<h6>
<%= mList[item].PaymentDescription%></h6>
<p>
<%= mList[item].PaymentDescription%></p>
</div>
<%
} %>
Code Behind
protected List<Payments_Default> mList;
protected int item;
public String PaymentCode { get; set; }
public String PaymentDescription { get; set; }
public int PaymentNumber { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
mList = new Payments_Default().GetPaymentTypes();
this.DataBind();
}
protected void AddItem()
{
item++;
}
protected List<Payments_Default> GetPaymentTypes()
{
List<Payments_Default> mList = new List<Payments_Default>();
Payments_Default mObject = null;
SqlCommand command = GenericSqlDataAccess.CreateCommandOnline("Text");
command.CommandText = "SELECT bla bla bla";
DataTable table = new DataTable();
table = GenericSqlDataAccess.ExecuteReader(command);
foreach (DataRow row in table.Rows)
{
mObject = new Payments_Default();
mObject.PaymentCode = row["PayTypeCode"].ToString();
mObject.PaymentDescription = row["PayTypeDesc"].ToString();
mObject.PaymentNumber = table.Rows.Count;
mList.Add(mObject);
}
return mList;
}

Categories