alert message when i select wrong in drop down list - javascript

I have two drop down list one lets assume ddl1 and ddl2. Both dropdown list bind hard coded in aspx page i want if i select ddl2 value if i selected some value suppose its not related to ddl1 value then show me alert message Please help me
My codes
public void BindSub()
{
Cmd = new SqlCommand("SP_P_BindSub", Con.OpenConnection());
Cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(Cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlSBU.DataSource = dt;
ddlSBU.DataValueField = "ID";
ddlSBU.DataTextField = "SBU_Name";
ddlSBU.DataBind();
ddlSBU.Items.Insert(0, new ListItem("Select", "0"));
}
protected void ddlSBU_SelectedIndexChanged(object sender, EventArgs e)
{
Cmd = new SqlCommand("SP_P_BindDepartment", Con.OpenConnection());
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.AddWithValue("#SBU_ID", ddlSBU.SelectedValue);
SqlDataAdapter da = new SqlDataAdapter(Cmd);
DataTable dt = new DataTable();
da.Fill(dt);
ddlDepartment.DataSource = dt;
ddlDepartment.DataValueField = "ID";
ddlDepartment.DataTextField = "Department_Name";
ddlDepartment.DataBind();
ddlDepartment.Items.Insert(0, new ListItem("Select", "0"));
}
<script >
$(document).ready(function () {
$("#ddlemployeetype").change(function () {
value1 = document.getelementbytext("ddlemployeetype").value;
value2 = document.getelementbytext("ddlrole").value;
case "Employee":
document.getElementById("subcategory").options[0] = new Option("select", "");
document.getElementById("subcategory").options[1] = new Option("Cordinator", "Cordinator");
document.getElementById("subcategory").options[2] = new Option("Filecer", "Filecer");
break;
case "Contractor":
document.getElementById("subcategory").options[0] = new Option("select", "");
document.getElementById("subcategory").options[1] = new Option("Leader", "Leader");
document.getElementById("subcategory").options[2] = new Option("Member", "Member");
break;
break;
return true;
if (value1 != value2) {
alert("not related value");
}
});
});
</script>
my ddl1 values are Contractor and employee and ddl2 values are cordinator, leader, facilator, leader2, member.
Condition : facilator and cordinator belongs to employee if i selected somthing other then show me message its wrong selection

You can do this by using jQuery:
$(document).ready(function () {
$("#ddl1").change(function () {
value1 = document.getElementById("ddl1").value;
value2 = document.getElementById("ddl2").value;
// here write your business logic
if (value1 != value2) {
alert("not related value");
}
});
});

Related

Call function on ButtonClick

I am trying to call function from .aspx to my JavaScript.
I try something like this
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Filter" Width="224px" OnClientClick="return BindToData();" />
And here is my JavaScript
<script type="text/javascript">
function GetSelectedReportName() {
return
document.getElementById('<%=ddlReportName.ClientID%>').options[document.getElementById('<%=ddlReportName.ClientID%>').selectedIndex].value;
}
function ShowReport() {
var reportName = GetSelectedReportName();
ASPxWebDocumentViewer1.OpenReport(reportName);
}
</script>
And here is my function which I need to call in ButtonClick
public void BindToData()
{
try
{
string connString = #"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
SqlConnection conn = new SqlConnection(connString);
string strproc = "TestReport";
using (SqlDataAdapter sda = new SqlDataAdapter(strproc, connString))
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
sda.SelectCommand.Parameters.Add("#Status", SqlDbType.Bit).Value = ddlStatus.SelectedValue == "1" ? true : false;
sda.SelectCommand.Parameters.Add("#OrgJed", SqlDbType.Int).Value = ddlOrgUnit.SelectedValue;
sda.Fill(ds);
XtraReport report = new XtraReport
{
DataSource = ds,
DataMember = ds.Tables[0].TableName
};
string[] arrvalues = new string[ds.Tables[0].Rows.Count];
for (int loopcounter = 0; loopcounter < ds.Tables[0].Rows.Count; loopcounter++)
{
//assign dataset values to array
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["PrezimeIme"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["NetworkLogin"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["Status"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["OrgUnitID"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["DT_Creat"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["DT_Modif"].ToString();
}
ASPxWebDocumentViewer1.OpenReport(report);
ASPxWebDocumentViewer1.DataBind();
//gridview1.DataSource = ds;
//gridview1.DataBind();
}
}
catch (Exception)
{
throw;
}
}
I need to load filtered report in button click, since in JS I only load report, when I click in button I get only unfiltered data, when I debug application I see that I get filtered data, but problem can be only in JS. Any help will be appreciate
Here is reference page which I check:
Link 1
Link 2
Link 3

Unable to save to DB, string was not recognized as a valid DateTime MVC

I have two text boxes that are enabled based on a checkbox. If checked == true then enable editing. Until this point everything is fine. However, when I hit the Submit button to save it to the database, it's not working. I was able to save it with just one of the text boxes being editable. Now that I have two editable boxes, it's not working.
Problem:
The ajax call is sending the dates and the ID back to the controller method. However, it's not getting saved to the DB. In UpdatePlannedDate I put in a couple breakpoints, its completely skipping over the first forEach loop.
The Exception it's throwing:
String was not recognized as a valid DateTime.
Model Class:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? Date1{ get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime? Date2{ get; set; }
public string R_ID { get; set; }
public string U_ID { get; set; }
public string C_ID { get; set; }
Controller class:
[HttpPost]
public JsonResult UpdatePlannedDate(string ids, string Date1, string Date2)
{
model = new Hello();
Entity db = new Entity();
List<Hello> list = new List<Hello>();
string[] IDS = ids.Split(',');
string[] Date1S = Date1.Split(',');
string[] Date2S = Date2.Split(',');
try
{
for (int i = 0; i < IDS.Length; i++)
{
if (IDS[i] != null && IDS[i] != "")
{
Hello item = new Hello { R_ID = IDS[i], Date_Two = DateTime.Parse(Date2S[i]), Date_One = DateTime.Parse(Date1S[i]) };
list.Add(item);
}
}
foreach (var row in db.table1)
{
foreach (var row2 in db.table2)
{
if (row.U_ID == row2.C_ID)
{
foreach (var item in list)
{
if (row.U_ID == item.R_ID)
{
var cd = db.Table2.Where(x => x.C_ID == row.U_ID).First();
cd.PlanDate = Convert.ToDateTime(item.Date_Two);
cd.PlanDate = Convert.ToDateTime(item.Date_One);
}
}
}
}
}
db.SaveChanges();
return Json(new { success = true, msg = "Updated" });
}
catch (Exception ex)
{
return Json(new { success = false, msg = ex.Message });
}
}
View class:
$(document).ready(function () {
var ids = "";
var date1 = "";
var date2 = "";
//Save to DB
$("#btnSubmit").bind("click", function () {
createUpdateArrays();
var url = "/Sample/UpdatePlannedDate";
$.ajax({
type: "POST",
url: url,
data: { ids: ids, date1: date1, date2: date2 },
success: function (data) {
if (data.success) {
$('.msg').html('Updated');
}
else {
alert("error");
}
}
});
ids = "";
date1 = "";
date2 = "";
});
function createUpdateArrays() {
var i = 0;
$('input.remedy-id:checkbox').each(function () {
if ($(this).is(':checked')) {
var rid = $(this).attr("id");
$('.date2').each(function () {
var did = $(this).attr("id");
if (did === rid) {
var date_2 = $(this).val();
ids += rid + ",";
date2 += date_2 + ",";
}
});
$('.date1').each(function () {
var tid = $(this).attr("id");
if (tid === rid) {
var date_1 = $(this).val();
ids += rid + ",";
date1 += date_1 + ",";
}
});
};
});
};
<tr id="home">
<td><input class="id" type="checkbox" id=#item.R_ID/></td>
<td>#Html.DisplayFor(x => item.R_ID)</td>
<td><input class="date1" id=#item.R_ID type="text" value='#(item.Date1 == null ? "" : Convert.ToDateTime(item.Date1).ToString("MM/dd/yyy"))' readonly="readonly" /></td>
<td><input class="date2" id=#item.R_ID type="text" value='#(item.Date2 == null ? "" : Convert.ToDateTime(item.Date2).ToString("MM/dd/yyy"))' readonly="readonly" /></td>
</tr>
1) What is your ORM? Entity Framework?
2) Try to debug line:
Hello item = new Hello { R_ID = IDS[i], Date_Two = DateTime.Parse(Date2S[i]), Date_One = DateTime.Parse(Date1S[i]) };
3) Isn't datetime conversion twice there?
First Hello item = ... line, second there
cd.PlanDate = Convert.ToDateTime(item.Date_Two);
cd.PlanDate = Convert.ToDateTime(item.Date_One);
4) What will do the change:
cd.PlanDate = item.Date_Two;
cd.PlanDate = item.Date_One;
?
5) Isn't also a logical fault there to have assignation of 2 values to one variable here?
6) Do you have any javascript extension to your fields on side of Razor template? What format it will produce here if you will pick your time from calendar? Does it fits to your definition mask in model class? (
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
)

How to convert datatable to json string in c#

Its work perfect when data in the datatable is small i.e 10 columns and 300 rows. But when the amount of data in datatable is large it did not work.
Here is my code
[WebMethod]
public static string getData()
{
string _cs = "";
string _query = "";
OleDbConnection _conn = new OleDbConnection();
OleDbCommand _cmd = new OleDbCommand();
OleDbDataAdapter _da = new OleDbDataAdapter();
DataTable _dt = new DataTable();
try
{
_cs = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _path + ";Extended Properties= \"Excel 8.0;HDR=Yes;IMEX=1\";";
//_query = "SELECT * FROM [3123121288$A1:L290]"; work perfect
_query = "SELECT * FROM [3123121288$]"; //did not work
_conn.ConnectionString = _cs;
_cmd.Connection = _conn;
_cmd.CommandText = _query;
_da.SelectCommand = _cmd;
_da.Fill(_dt);
}
catch (Exception ex)
{ }
return JsonConvert.SerializeObject(_dt);
}

How populate database records into my table ajax

So i go this information and have a empty table name categorytable so i have to have records stored in categoryList for the below code to work. so what do i write in categoryList which is to fetch the record from my category manager and display the data from sql
</table>
<script>
$(document).ready(function () {
var categoryList = [];
var $courseTableElement = $('#categoryTable');
var $rowElement;
var $cellElement;
var index = 0;
for (index = 0; index < categoryList.length; index++) {
$rowElement = $('<tr></tr>');
$cellElement = $('<td></td>', { text: categoryList[index].CategoryName });
$rowElement.append($cellElement);
$cellElement = $('<td></td>', { text: categoryList[index].CategoryId });
$rowElement.append($cellElement);
$courseTableElement.append($rowElement);
}
});
</script>
public List<Category> getAllCategory(string inUserId)
{
DataSet ds = new DataSet();
List<Category> categoryList = new List<Category>();
string sqlText = "";
using (SqlConnection cn = new SqlConnection())
{
cn.ConnectionString =
ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = cn; //setup the
cn.Open();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
sqlText = "SELECT CategoryId,CategoryName,CreatedBy,CreatedAt,UpdatedBy,UpdatedAt " +
" FROM Category ";
cmd.CommandText = sqlText;
cmd.Parameters.Add("#inCurrentUserId", SqlDbType.VarChar, 200).Value = inUserId;
da.Fill(ds, "CategoryData");
cmd.CommandText = sqlText;
}//using SqlDataAdapter da
cn.Close();
}//using SQLCommand cmd
}//using SQLConnection cn
foreach (DataRow dr in ds.Tables["CategoryData"].Rows)
{
Category category = new Category();
category.CategoryId = Int32.Parse(dr["CategoryId"].ToString());
category.CategoryName = dr["CategoryName"].ToString();
category.CreatedBy = dr["CreatedBy"].ToString();
category.CreatedAt = DateTime.Parse(dr["CreatedAt"].ToString());
category.UpdatedBy = dr["UpdatedBy"].ToString();
category.UpdatedAt = DateTime.Parse(dr["UpdatedAt"].ToString());
categoryList.Add(category);
}
return categoryList;
}
You just need to make an ajax request to your server and grab that data. I'm making a couple of assumptions.
That getAllCategory is accessible to the frontend via webapi or something of the sort.
That getAllCategory will return proper json.
function getDataFromServer(url, callback){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("get",url);
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readystate === 4 && xmlhttp.status === 200){
//data was retrieved successfully.
callback(JSON.parse(xmlhttp.response));
}
}
xmlhttp.send();
}
$(document).ready(function () {
//the path to action must include the id in querystring
var url = 'path_to_action'
getDataFromServer(url, function(data){
var courseTableElement = $('#categoryTable');
for(var i = 0; i < data.length; i++){
var row = $('<tr></tr>');
var cell1 = $('<td></td>, { text: data[i].CategoryName } );
var cell2 = $('<td></td>, { text: data[i].CategoryId } );
row.append(cell1);
row.append(cell2);
courseTableElement.append(row);
}
}
});

How do I set my default checked checkbox on pageload for my latest date in checkboxlist instead of select all?

I have a checkboxlist in asp.net, populated by a stored procedure. While "Select All" option is done in aspx.
Currently im setting my "Select All" as default using javascript to do some enabling and disabling upon slect "Select All".
My problem now is that I do not want to set "Select All" as default but the latest date as default on page load? How can I do so when my dates are populated using stored procedure?
The below is how my checkboxlist lloks like with select all as default:
The below is what I want to achieve which is to get the latest date (2nd checkbox):
My codes for my checkboxlist:
<asp:CheckBoxList ID="Date_CBL" Class="checkboxlist" runat="server" AppendDataBoundItems="True" ViewStateMode="Enabled">
<asp:ListItem Text="Select All" Value="Select All"></asp:ListItem>
</asp:CheckBoxList>
My codes for javascript:
$(function () {
if ($("#hidden").val() == "") {
$("#Date_CBL :checkbox").removeAttr('disabled');
$("[id*=Date_CBL] input:checkbox").eq(1).prop("checked", true);
$("#hidden").val("set");
}
});
$(function () {
$("#Date_CBL :checkbox").change(function () {
var ischecked = $(this).is(":checked");
var val = $(this).val();
//alert(val);
if (val == "Select All") {
if (ischecked) {
$("#Date_CBL :checkbox").attr('disabled', 'disabled');
$(this).removeAttr('disabled');
$("#Date_CBL :checkbox").prop("checked", false);
$(this).prop("checked", true);
return;
} else {
$("#Date_CBL :checkbox").removeAttr('disabled');
return;
}
} else if (val != "Select All") {
if (ischecked) {
$("#Date_CBL :checkbox[value='Select All']").prop("checked", false);
}
}
});
});
My codes to populate my check box list:
using (SqlConnection conn = new SqlConnection(dbConn))
{
try //Call stored procedure
{
SqlCommand cmd = new SqlCommand(spddl, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
//Populate CheckBoxList list items from store procedure
if (!IsPostBack)
{
Date_CBL.DataSource = ds.Tables[0];
Date_CBL.DataTextField = ds.Tables[0].Columns["DATA_DATE"].ToString();
Date_CBL.DataValueField = ds.Tables[0].Columns["DATA_DATE"].ToString();
Date_CBL.DataBind();
Bindgridview()
}
conn.Close();
}
My codes in cs:
public void BindGridView()
{
DateTime choosenDate = DateTime.MinValue;
using (SqlConnection conn = new SqlConnection(dbConn))
{
using (SqlCommand cmd = new SqlCommand(spretrieve, conn))
{
//Bind selected CheckBoxList items into one string and pass into stored procedure as parameter
String selectedDATE = String.Empty;
if (Date_CBL.SelectedValue == "Select All")
{
selectedDATE = "DATA_DATE";
}
else
{
foreach (ListItem item in Date_CBL.Items)
{
if (item.Selected)
{
DateTime dtTemp = Convert.ToDateTime(item.Value);
selectedDATE += "'" + dtTemp.ToString("yyyy-MM-dd") + "',";
}
}
selectedDATE = selectedDATE.Substring(0, selectedDATE.Length - 1);
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#DATE", SqlDbType.VarChar).Value = selectedDATE;
string query = cmd.CommandText;
//Populate grid view
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
Gridview1.DataSource = ds.Tables[0];
Gridview1.DataBind();
Thus how can I always set my latest date which will be the 2nd check box to be default upon page load?
Please advice thanks.
You might need to go learn about Page Event
What load first...
UPDATE CODE
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Variable
string dbConn = string.Empty;
string spddl = string.Empty;
// CHeck
if (!IsPostBack)
{
using (SqlConnection conn = new SqlConnection(dbConn))
{
// Error Handling
try { conn.Open(); }
catch (Exception ex) { throw ex; }
SqlCommand cmd = new SqlCommand(spddl, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
// Error Handling
try { da.Fill(ds); }
catch (Exception ex) { throw ex; }
Date_CBL.DataSource = ds.Tables[0];
Date_CBL.DataTextField = ds.Tables[0].Columns["DATA_DATE"].ToString();
Date_CBL.DataValueField = ds.Tables[0].Columns["DATA_DATE"].ToString();
Date_CBL.DataBind();
// Must Check From Code Behind since you are using it to before Page_Load.. Javascript will work after your Page Show Everything
Date_CBL.Items[1].Selected = true; // Check 2nd Item
BindGridView(conn);
conn.Close();
}
}
}
private void BindGridView(SqlConnection conn)
{
string spretrieve = string.Empty;
string selectedDATE = String.Empty;
using (SqlCommand cmd = new SqlCommand(spretrieve, conn))
{
//Bind selected CheckBoxList items into one string and pass into stored procedure as parameter
// This Will be wrong if you use selected Value
if (Date_CBL.Items[0].Selected == true)
{
selectedDATE = "DATA_DATE";
}
else
{
foreach (ListItem item in Date_CBL.Items)
{
if (item.Selected)
{
DateTime dtTemp = Convert.ToDateTime(item.Value);
selectedDATE += "'" + dtTemp.ToString("yyyy-MM-dd") + "',";
}
}
selectedDATE = selectedDATE.TrimEnd(','); // Don't use substring cause last length is the comma u can use trimEnd
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#DATE", SqlDbType.VarChar).Value = selectedDATE;
string query = cmd.CommandText;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
try { da.Fill(ds); }
catch (Exception ex) { throw ex; }
Gridview1.DataSource = ds.Tables[0];
Gridview1.DataBind();
}
}
$(function () {
var $all = $("#Date_CBL ").find(":checkbox");
var $first = $all.eq(1);
$first.prop("checked", true);
});

Categories

Resources