I have this code which works fine as long as as dt.Value is different to "int".
This is the line which errors:
(dt.Value.ToLower().Substring(0, 4).Equals("date"))
It works fine if dt.Value is varchar or datetime.
I provided my suggested solution at the end of this post.
// Edit
if (e.CommandName == "Edit")
{
// Get the item
RepeaterItem Item = ((RepeaterItem)((Button)e.CommandSource).NamingContainer);
// Get buttons and repeater
Button savebtn = (Button)(Item.FindControl("btnSave"));
Button editbtn = (Button)(Item.FindControl("btnEdit"));
Repeater rFields = (Repeater)(Item.FindControl("repFields"));
// Enable my fields
foreach (RepeaterItem RI in rFields.Items)
{
// Get data type
HiddenField dt = (HiddenField)(RI.FindControl("hdnDBDataType"));
// Set controls
if (RI.FindControl("chkSetting").Visible) ((CheckBox)RI.FindControl("chkSetting")).Enabled = true;
if (RI.FindControl("ddlSetting").Visible) ((DropDownList)RI.FindControl("ddlSetting")).Enabled = true;
if (RI.FindControl("txtSetting").Visible)
{
((TextBox)RI.FindControl("txtSetting")).Enabled = true;
// Check my data type
if (dt.Value.ToLower().Substring(0, 4).Equals("date")) ((CalendarExtender)RI.FindControl("extDateTime")).Enabled = true;
}
}
}
Is this a good fix ? TIA
if(dt.Value != "int" && dt.Value.ToLower().Substring(0, 4).Equals("date"))
Substring will throw an error if the second parameter is higher than the lenght of the string. What you need to do is check the length before doing the substring or use a method like #Igor suggested in the comments.
Your suggestion to check != "int" is not fullproof if let's say somehow the value is any string less than 4 characters.
(dt.Value.Length > 3 && dt.Value.ToLower().Substring(0, 4).Equals("date"))
I will also put #Igor suggestion here because it is also fullproof:
(dt.Value.StartsWith("date", StringComparison.OrdinalIgnoreCase)
How to validate whether the text in multiple textboxes are unique from each other.
It looks like that in asp.net but its not a valid syntax
bool hasNoDuplicate = (txtEmergencyName1.Text.Trim() <> txtEmergencyName2.Text.Trim() <> txtEmergencyName3.Text.Trim <> txtEmergencyName4.Text.Trim);
I am looking for an efficient appraoch, kind of lambda expression or inbuilt in asp.net
Since you're asking for lambda, here's a linq approach.
var allTxt = new[] { txtEmergencyName1, txtEmergencyName2, txtEmergencyName3, txtEmergencyName4 };
var allText = allTxt.Select((txt, i) => new { Text = txt.Text.Trim(), Pos = i + 1 }).ToList();
bool hasNoDuplicate = !allText.Any(t => allText.Skip(t.Pos).Any(t2 => t.Text == t2.Text));
Put all relevant TextBoxes in a collection like an array and use Enumerable.Any. By skipping all before the current textbox you avoid checking the TextBoxes twice.
If all relevant TextBoxes are in a container control like a Panel, you could also use Enumerable.OfType to find them:
IEnumerable<TextBox> allTxt = this.EmergencyPanel.Controls.OfType<TextBox>();
Side-note: it's premature optimization anyway to look for the most performant way to validate some controls. This is nothing what you are doing constantly and there are never millions of controls. Instead you should look for the shortest or most readable approach.
You can use and && or or || operator accordingly
bool isDuplicate=(txtEmergencyName1.Text.Trim() == txtEmergencyName2.Text.Trim()
&& txtEmergencyName2.Text.Trim() == txtEmergencyName3.Text.Trim);
it will set true or false in the isDuplicate variable.
Edit 1
bool isDuplicate=(txtEmergencyName1.Text.Trim() == txtEmergencyName2.Text.Trim()
&& txtEmergencyName2.Text.Trim() == txtEmergencyName3.Text.Trim
&& txtEmergencyName1.Text.Trim() == txtEmergencyName3.Text.Trim
);
You could also do something like
var test = new TextBox();
var AlltBox = new List<TextBox>() { new TextBox() };
for(int i=1; i == 5;i++)
AlltBox.Add((TextBox)this.FindName("txtEmergencyName"+i));
bool exist = AlltBox.Any(tb => ((tb.Text == test.Text)&& tb.Name != test.Name));
but i don't know about the performance
Item_SubContractor Item = (
from Isc in db.Item_SubContractors
where Isc.SubContract_id == tempSubContractId
&& Isc.Item_id == BOQItem.id
select Isc).ToList().FirstOrDefault();
Item is returning NULL, when db.Item_SubContractors, tempSubContractId, BOQItem.id all return something when I break point and run through it
Someone has any ideas how can I solve this problem?
Thanks
the FirstOrDefault() will return NULL if you don't have the value in your Database then be sure that the same item exist in your database
you can test this
bool exist = db.Item_SubContractors.Any(
Isc=> Isc.SubContract_id == tempSubContractId
&& Isc.Item_id == BOQItem.id)
to check if you have this item in your database
ternary make code concise and readable, I'm curious about how to change the following if condition to ternary operator:
var1 = if(true){'a'};
I try the following
var1 = true? 'a': ;
since it require nothing to do with false condition, I leave blank after :, but apparently it gives me a error.
Is there a way to do this?
--------update---------
The intention of using the above example is that I want to simplify the problem, however it made everyone more confuse, so I post my original code:
if($_SERVER['REQUEST_METHOD'] == 'GET'){ $sub_count = 0; }
$sub_count = $_SERVER['REQUEST_METHOD'] == 'GET'? 0 : ;
how to change the if condition to ternary ?
$sub_count = null;
$sub_count = $_SERVER['REQUEST_METHOD'] == 'GET'? 0 : null;
// To check:
if(!isset($sub_count))
{
// Do something because $_SERVER['REQUEST_METHOD'] != 'GET'
} else {
if($sub_count===0)
{
// REQUEST METHOD IS GET
}
}
all
I am trying to use #Html.CheckBoxFor.
Here is my code:
Model:
public bool WC0001 { get; set; }
View:
#using (Html.BeginForm("ListSearch", "Committee", FormMethod.Get))
{
#Html.CheckBoxFor(model => model.WC0001) <label for="WC0001" class="mrg_r20">Development</label>
}
I am using WebGrid as well.
When I click page 2, I get this error.
Cannot implicitly convert type 'string' to 'bool'
So I looked at the url.
It is "http://localhost:28685/Committee/ListSearch?WC0001=true%2cfalse&page=2"
Why do I get WC0001 parameter as true%2cfalse?
And what is the workaround for this?
It didn't happen when I used to post the form.
But since I changed it as FormMethod.Get because of WebGrid, it started to occur.
Please somebody help me.
EDIT:
This is what happens, when reload the page.
EDIT:
Here is my action code:
[HttpGet]
public ActionResult ListSearch(Kuksiwon.Models.Committee profile, FormCollection collection)
{
DataTable _dt = _bp.DtReturnS(false
, "WSP_KW100_R1"
, profile.APJIKJONGCODE == null ? "" : profile.APJIKJONGCODE
, profile.APKUKSICODE == null ? "" : profile.APKUKSICODE
, profile.CTNAME == null ? "" : profile.CTNAME
, collection["CTSEXList"] == null ? "" : collection["CTSEXList"].ToString()
, profile.CTOADDRESS1 == null ? "" : profile.CTOADDRESS1
, profile.CTOADDRESS2 == null ? "" : profile.CTOADDRESS2
, profile.CTUNIVCODE1 == null ? "" : profile.CTUNIVCODE1
, profile.CTHOSPCODE1 == null ? "" : profile.CTHOSPCODE1
, profile.CTETCNAME == null ? "" : profile.CTETCNAME
, profile.CTUNIVDIV1 == null ? "" : profile.CTUNIVDIV1
, profile.CTUNIVJIKUP1 == null ? "" : profile.CTUNIVJIKUP1
, profile.CTEMAIL == null ? "" : profile.CTEMAIL
, profile.WC0001 ? "WC0001" : ""
, profile.WC0002 ? "WC0002" : ""
, profile.WC0003 ? "WC0003" : ""
, profile.WC0004 ? "WC0004" : ""
, profile.WC0005 ? "WC0005" : ""
, profile.WC0006 ? "WC0006" : ""
, profile.WC0007 ? "WC0007" : ""
, profile.WC0008 ? "WC0008" : ""
, profile.WCNONE ? "1" : "0"
, profile.RSNAME == null ? "" : profile.RSNAME
, profile.BKNAME == null ? "" : profile.BKNAME
, profile.CTSUBJECT == null ? "" : profile.CTSUBJECT
, profile.CTCOLLEGE == null ? "" : profile.CTCOLLEGE
);
ViewBag.ListSearch = _dt;
profile.CTSEXList = profile.CommonCodeList("SX", "1");
return View(profile);
}
This is a bug (well, I consider it a bug) in what MVC spits out for #Html.CheckBoxFor()-- it spits on the actual input checkbox, but also a hidden field with the same name. They're doing this so that an HTTP post will have the default value (if the checkbox is unchecked) still sent along with the data. But for a GET, the browser is sending both values in the querystring, causing it to come out on the server as a string array (leading to your exception).
Here's the jQuery I ended up using to disable the hidden fields if their checkboxes are checked (disabled fields never get sent via FORM submissions). Stick this in your document ready logic:
$('input[type=checkbox] ~ input[type=hidden]').each(function() {
var curHiddenField = $(this);
var checkBox = curHiddenField.prev();
checkBox.change(function () {
curHiddenField.val(checkBox[0].checked);
if (checkBox[0].checked) {
curHiddenField.attr('disabled', 'disabled');
} else {
curHiddenField.removeAttr('disabled');
}
}).change();
});
The only possible reason I can think of that would cause this issue is if your ModelState were modified with an invalid value. That would be the only way to get the error while rendering the page.
You should check the ModelState in your controller like this:
var wc0001 = ModelState["WC0001"].Value;
var raw = wc0001.RawValue; // Should be ["true", "false"]
var attempted = wc0001.AttemptedValue; // Should be "true,false"
var converted = wc0001.ConvertTo(typeof(bool)); // If this fails, then Html.CheckBoxFor will fail too.
Update:
After looking at your action method, I don't see anything that would cause an invalid ModelState. Please let me know the values of .RawValue and .AttemptedValue because those will probably have some clue as to the cause of this problem.
After doing some testing, I think I might have figured out your problem.
As you probably know, rendering a CheckBox results in a an <input type="checkbox" /> and an <input type="hidden" /> with the same name. If the checkbox is checked, when the form is submitted, the GET/POST will have duplicate entries for that field:
ListSearch?WC0001=true&WC0001=false
MVC treats these values as an array of strings ["true", "false"], and when it binds to a bool, it only parses the first array item.
You might have already realized the problem now. Your sample URL has combined these values into:
ListSearch?WC0001=true,false
MVC will treat this value as a single string "true,false", which means it will FAIL to bind to a bool!
The problem is almost certainly caused by some JavaScript that is creating the URL, and the script is probably trying to be smart and combine duplicate inputs into a comma-separated list. This won't work for MVC, though, so you need to keep the values separate.