Answered by:
ASP.net, C#, Website, Javascript, DropDownList How to Parse Guid

Question
-
User1045460610 posted
I have this script that works with the recordID as type Integer, but when I change to type to guid the dropdownlist doesn't populate. I think the error is that I need to parseGuid. I don't see a parseGuid builtin for Javascript.
On this line below recordID = parseInt(temp[0]), how do I parse the Guid?
code behind listing
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;public partial class updatecourses : System.Web.UI.Page
{protected void Page_LoadComplete(object sender, EventArgs e)
{{
SqlConnection con = new SqlConnection(Database.ConnectionString);
try
{
var returnUrl = Request.Params["ReturnUrl"];
var hostID = Request.Params["HostID"];
if (string.IsNullOrWhiteSpace(hostID))
{
if (!string.IsNullOrWhiteSpace(returnUrl))
Response.Redirect(returnUrl);throw new Exception("Variable \"HostID\" not found in query params");
}con.Open();
var cmd = new SqlCommand("select * from dbo.FWK_User where HostID = @hostId", con);
cmd.Parameters.AddWithValue("hostId", hostID);
var dr = cmd.ExecuteReader();
if (!dr.Read())
Response.Redirect($"studentcourse.aspx?hostId={hostID}"); // won't need to redirect, instructor will click link on web site for Faculty (Instrcutor) or student
dr.Close();var query = @"select distinct" +
" flt.instrctr_id_num as HostID" +
",sd.scheduledaysid as RecordID" +
",sd.status" +
",sd.minutes" +
",sm.crs_cde as CourseCode" +
",sm.SHORT_CRS_TITLE_1 as CourseTitle" +
",sm.yr_cde,sm.trm_cde" +
",sd.startTime as StartTime" +
",sd.startTime" +
",flt.instrctr_id_num as InstructorID" +
",n.First_Name" +
", CONCAT(n.LAST_NAME, ', ', n.FIRST_NAME) AS InstructorName" +
" from net.dbo.ScheduleDays as sd" +
" inner join net.dbo.lms_section as s" +
" on sd.sectionid = s.SectionID " +
"inner JOIN net.dbo.LMS_Course AS c " +
"WITH (NOLOCK) ON s.CourseID = c.CourseID " +
"inner join tmprd.dbo.section_master as sm" +
" on c.CourseCode + ' ' + s.NAME = sm.crs_cde " +
"and left(s.coursekey,4) = sm.yr_cde " +
"and substring(s.CourseKey,6,2) = sm.trm_cde " +
"inner join tmprd.dbo.student_crs_hist as sch " +
"on sm.crs_cde = sch.crs_cde " +
"and sm.yr_cde = sch.yr_cde " +
"and sm.trm_cde = sch.trm_cde " +
"inner join tmprd.dbo.faculty_load_table " +
"as flt on sm.crs_cde = flt.crs_cde " +
"and sm.yr_cde = flt.yr_cde " +
"and sm.trm_cde = flt.trm_cde " +
"inner join TmPrd.dbo.NAME_MASTER " +
"as n on n.id_num = flt.instrctr_id_num " +
"where " +"sd.startdate <= @Now " +
"and sd.enddate >= @Now " +"and flt.INSTRCTR_ID_NUM = @HostID " +
"and sm.crs_cde not like 'ONSO%'" +
"AND sm.CRS_CDE NOT LIKE 'CLIN 7303 001' " +
"AND sm.CRS_CDE NOT LIKE 'CLIN 7203 001' " +
"AND sm.CRS_CDE NOT LIKE 'CLIN 8103 001' " +
"and sm.LOC_CDE = 'main'";cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("HostID", hostID);
cmd.Parameters.AddWithValue("RecordID", txtRecordID.Text);
cmd.Parameters.AddWithValue("now", DateTime.Now);dr = cmd.ExecuteReader();
if (dr.Read())
{
// display data in textboxes
txtRecordID.Text = dr["RecordID"].ToString();
txtInstructorID.Text = dr["InstructorID"].ToString();
txtInstructorName.Text = dr["InstructorName"].ToString();
txtCourseCode.Text = dr["CourseCode"].ToString();
txtCourseTitle.Text = dr["CourseTitle"].ToString();
txtStartTime.Text = dr["StartTime"].ToString();
txtAttendanceCode.Text = dr["AttendanceCode"].ToString();
}
else
{
lblMsg3.Text = "You do not have a class in the next hour.";
}
dr.Close();
}
//catch (Exception ex)
catch (Exception)
{
//lblMsg.Text = "Error --> " + ex.Message;
}
finally
{
con.Close();
}if (string.IsNullOrWhiteSpace(txtAttendanceCode.Text))
{
string numbers = "1234567890";string characters = numbers;
int length = 5;
string otp = string.Empty;
for (int i = 0; i < length; i++)
{
string character = string.Empty;
do
{
int index = new Random().Next(0, 5);
character = characters.ToCharArray()[index].ToString();
} while (otp.IndexOf(character) != -1);
otp += character;
}
txtAttendanceCode.Text = otp;
}
}}
protected void BtnGenerateCode_Click(object sender, EventArgs e)
{
{
string numbers = "1234567890";string characters = numbers;
int length = 5;
string otp = string.Empty;
for (int i = 0; i < length; i++)
{
string character = string.Empty;
do
{
int index = new Random().Next(0, 5);
character = characters.ToCharArray()[index].ToString();
} while (otp.IndexOf(character) != -1);
otp += character;
}
txtAttendanceCode.Text = otp;
}}
[WebMethod]
public static string GetCourseTitles(string instructorId)
{
var result = new List<dynamic>();
SqlConnection con = new SqlConnection(Database.ConnectionString);
try
{
con.Open();
var cmd = new SqlCommand("select distinct" +
" sd.scheduledaysid as RecordID " + //guid, need to change course guid, not instructor ID
",sm.crs_cde as CourseCode" + //1 coursecode is second column
",sm.SHORT_CRS_TITLE_1 as CourseTitle" + //2 title is third column
" from net.dbo.ScheduleDays as sd" +
" inner join net.dbo.lms_section as s" +
" on sd.sectionid = s.SectionID" +
" inner JOIN net.dbo.Course AS c" +
" WITH (NOLOCK) ON s.CourseID = c.CourseID" +
" inner join tmprd.dbo.section_master as sm" +
" on c.CourseCode + ' ' + s.NAME = sm.crs_cde" +
" and left(s.coursekey,4) = sm.yr_cde" +
" and substring(s.CourseKey,6,2) = sm.trm_cde" +
" inner join tmprd.dbo.student_crs_hist as sch" +
" on sm.crs_cde = sch.crs_cde" +
" and sm.yr_cde = sch.yr_cde" +
" and sm.trm_cde = sch.trm_cde" +
" inner join tmprd.dbo.faculty_load_table" +
" as flt on sm.crs_cde = flt.crs_cde" +
" and sm.yr_cde = flt.yr_cde" +
" and sm.trm_cde = flt.trm_cde" +
" inner join TmPrd.dbo.NAME_MASTER" +
" as n on n.id_num = flt.instrctr_id_num " +"where " +
"flt.instrctr_id_num = @instructorId " + //courses for current instructor
"and sm.crs_cde not like 'ONSO%' " +
"AND sm.CRS_CDE NOT LIKE 'CLIN 7303 001' " +
"AND sm.CRS_CDE NOT LIKE 'CLIN 7203 001' " +
"AND sm.CRS_CDE NOT LIKE 'CLIN 8103 001' " +
"and sm.LOC_CDE = 'main'", con);cmd.Parameters.AddWithValue("instructorId", instructorId);
var reader = cmd.ExecuteReader();
while (reader.Read()) //reader, reading through results, adding records to dropdownlist
{
result.Add(new
{
//RecordID = reader.GetInt32(0), //instrctr_id_num //{"Specified cast is not valid."}
RecordID = reader.GetGuid(0),CourseCode = reader.GetString(1),
Title = reader.GetString(2)
});
}
reader.Close();
}
//catch (Exception ex)
catch (Exception)
{
//lblMsg4.Text = "Error --> " + ex.Message;
}finally
{
con.Close();
}
return JsonConvert.SerializeObject(result); //not returning result to web page, browserLink doesn't seem to run
}
protected void Page_Load(object sender, EventArgs e)
{}
protected void btnAdd_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(Database.ConnectionString);
try
{
con.Open(); //SqlCommand cmd = new SqlCommand("insert into Reporting.dbo.InstructorCourse(RecordID,InstructorID,CourseID,CourseCode,CourseTitle,AttendanceCode) values(@RecordID,@InstructorID,@CourseID,@CourseCode,@CourseTitle,@AttendanceCode)", con);
cmd.Parameters.AddWithValue("@RecordID", txtRecordID.Text); //scheduledaysid guid, dropdownlist changes value
cmd.Parameters.AddWithValue("@InstructorID", txtInstructorID.Text);
cmd.Parameters.AddWithValue("@CourseID", txtRecordID.Text); //reserved for unique value, dropdownlist changes value
cmd.Parameters.AddWithValue("@CourseCode", txtCourseCode.Text); //like CHS 6102 001 L, dropdownlist changes value
cmd.Parameters.AddWithValue("@CourseTitle", txtCourseTitle.Text); //dropdownlist changes value
cmd.Parameters.AddWithValue("@AttendanceCode", txtAttendanceCode.Text);int count = cmd.ExecuteNonQuery();
if (count == 1)
lblMsg3.Text = "Attendance Code [" + txtCourseCode.Text + "] has been recorded!";
else
lblMsg3.Text = "Could not add Attendance!";
}
catch (Exception ex)
{
lblMsg3.Text = "Error --> " + ex.Message;
}
finally
{
con.Close();
}
}
}<%@ Page Language="C#" AutoEventWireup="true" CodeFile="instructorcourse.aspx.cs" Inherits="updatecourses" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head3" runat="server">
<title>On Grounds</title>
<style type="text/css">
.auto-style1 {
width: 30px;
}.auto-style2 {
width: 132px;
}.auto-style5 {
width: 24px;
}
.auto-style7 {
width: 140px;
height: 26px;
}
.auto-style8 {
width: 24px;
height: 26px;
}
.auto-style9 {
width: 273px;
}
.auto-style10 {
width: 123px;
}
.auto-style11 {
width: 123px;
height: 26px;
}
.auto-style12 {
/*width: 140px;*/
}
</style>
</head>
<body>
<%--<script>JavaScript is Active</script>
<noscript>JavaScript is Disabled</noscript>--%>
<form id="form3" runat="server">
<h2 class="auto-style9">
<asp:Image ID="Image1" runat="server" Height="103px" Width="216px" ImageUrl="~/headerLogo.png" />
</h2>
<h2>Attendance</h2>
<h2>Intructor - Next Course</h2>
<table>
<tr>
<td class="auto-style10">Insctructor ID:</td>
<td class="auto-style12">
<asp:TextBox ID="txtInstructorID" runat="server" Enabled="False"></asp:TextBox></td>
<td class="auto-style5"></td>
</tr>
<tr>
<td class="auto-style11">Instructor Name:</td>
<td class="auto-style7">
<asp:TextBox ID="txtInstructorName" runat="server" Enabled="False"></asp:TextBox></td>
<td class="auto-style8"></td>
</tr>
<tr>
<td class="auto-style10">Course Code:</td>
<td class="auto-style12">
<asp:TextBox ID="txtCourseCode" runat="server" Enabled="False"></asp:TextBox></td>
<td class="auto-style5"> </td>
</tr><tr>
<td class="auto-style10">Course Title:</td>
<td class="auto-style12">
<asp:TextBox ID="txtCourseTitle" runat="server" Enabled="False"></asp:TextBox></td>
<td class="auto-style5">
<select name="DropDownList1" id="DropDownList1" onchange="changeCourse(event)">
</select> <%--on change, populates text boxes with result, then should call browserLink function, not calling now--%>
</td>
</tr>
<tr>
<td class="auto-style10">Course StartTime:</td>
<td class="auto-style12">
<asp:TextBox ID="txtStartTime" runat="server" Enabled="False"></asp:TextBox></td>
</tr>
<tr>
<td class="auto-style10">Attendance Code: </td>
<td class="auto-style12">
<asp:TextBox ID="txtAttendanceCode" runat="server" ToolTip="Use the System Generated Random Code or click the Code Button to Generate a New Code, Youn can alsto Enter Your Own Code!"></asp:TextBox>
</td>
<td class="auto-style5">
<asp:Button ID="btnGenerateCode" runat="server" OnClick="BtnGenerateCode_Click" Text="Code" />
</td>
</tr>
</table>
<br />
<asp:Button ID="btnAdd" runat="server" Text="Save Code" OnClick="btnAdd_Click" />
<br />
<br />
<asp:Button ID="btnHelp" runat="server" Text="?" ToolTip="Instructions/Notes: You can use the system generated code or create your own. We recommend that it is user-friendly. All codes are unique to this course. Click Save Code to capture the attendance code for this course session. Students must be in this class and on the Parker U wireless network to post their attendance. If students do not have a smartphone or laptop, you can allow them to log in to MyParker at the podium. " />
<br />
<br />
<asp:Label ID="lblMsg3" runat="server" EnableViewState="False"></asp:Label>
<br />
<asp:Panel ID="Panel1" runat="server" Width="267px">
<%--<br />
Instructions/Notes:
<br />
-You can use the system generated code or create your own. We recommend that it is user-friendly.
<br />
-All codes are unique to this course.
<br />
-Click Save Code to capture the attendance code for this course session.
<br />
-Students must be in this class and on the Parker U wireless network to post their attendance.
<br />
-If students do not have a smartphone or laptop, you can allow them to log in to MyParker at the podium.--%>
</asp:Panel>
<asp:Label ID="lblMsg2" runat="server" EnableViewState="False"></asp:Label>
<br />
<asp:Label ID="lblMsg4" runat="server" EnableViewState="False"></asp:Label>
<br />
<br />
<table>
<tr>
<%--<td class="auto-style4">Record ID: </td>--%>
<td class="auto-style2">
<asp:TextBox ID="txtRecordID" runat="server" Enabled="False" Width="266px"></asp:TextBox>
</td>
<td class="auto-style1">
<%-- will select next course on form load, by hostid, will go in form load</tr>--%></table>
<br />
<br />
</form>
<script type="text/javascript">
function load() {
var xhttp = new XMLHttpRequest();
xhttp.open('post', 'instructorcourse.aspx/GetCourseTitles', true);
xhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhttp.setRequestHeader('Content-Type', 'application/json');
xhttp.onreadystatechange = function () {
if (xhttp.readyState == XMLHttpRequest.DONE && xhttp.status == 200) {
var $titlesDropDown = document.getElementById('DropDownList1'),
courses = JSON.parse(JSON.parse(this.responseText).d),
html = '';
courses.forEach(function (course) {
var value = course.RecordID + '|' + course.CourseCode + '|' + course.Title;
html += '<option value="' + value + '">' + course.Title + '</option>';
});
$titlesDropDown.innerHTML = html;
}
};
xhttp.send(JSON.stringify({ instructorId: '<%=txtInstructorID.Text%>' }));
}
document.addEventListener('DOMContentLoaded', load);function changeCourse(e) {
var temp = e.target.value.split('|'),
recordID = parseInt(temp[0]),
courseCode = temp[1],
title = temp[2];
<%--document.getElementById('<%=nameof(txtInstructorID)%>').value = recordID;--%>
document.getElementById('<%=nameof(txtRecordID)%>').value = recordID;
document.getElementById('<%=nameof(txtCourseCode)%>').value = courseCode;
document.getElementById('<%=nameof(txtCourseTitle)%>').value = title;
}
</script>
</body>
</html>Tuesday, April 9, 2019 8:36 PM
Answers
-
User-1174608757 posted
Hi Tom4lT,
According to your description, I have made a sample here. I find it works well and I could directly use Json.Parse to get the value of Guid.So, you could follow the steps as mine or you could use chrome broswer and F12 to see whether there esxits any problems. Here is my demo, I hope it could help you.
Asmx;
/// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. public class check { public string name { get; set; } public Guid work { get; set; } } [System.Web.Script.Services.ScriptService] public class W1 : System.Web.Services.WebService { check cll = new check(); [WebMethod] public string HelloWorld() { cll.name = "test1"; cll.work = System.Guid.NewGuid();// this is attribute which value is Guid return JsonConvert.SerializeObject(cll); } }
ASPX:
<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="../Scripts/jquery-3.3.1.js"></script> <script> $(function () { $.ajax({ type: "POST", url: "W1.asmx/HelloWorld", contentType: "application/json", dataType:"text", success: function (data) { console.log(JSON.parse(JSON.parse(data).d).work); var x = document.getElementById("DropDownList1"); var option = document.createElement("option"); option.text = JSON.parse(JSON.parse(data).d).work;// get the Guid value of attribute and set as the option of dropdownlist x.add(option); }, error: function (e) { console.log(e); } }) }) </script> </head> <body> <form id="form1" runat="server"> <div> <asp:DropDownList ID="DropDownList1" runat="server"> </asp:DropDownList> </div> </form> </body> </html>
You could see:
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Wednesday, April 10, 2019 3:17 AM