Check if a GET method is Null/Empty - c#

I have recently been working with a <select> tag, however, I have noticed you cannot determine, using an if statement if the GET is NULL or equal to "".
var tbl_st = (from c in db.tblfsk_style select c).ToArray();
build.Append("<select id='style' name='style' class='styles'>");
foreach (var style in tbl_st)
{
build.Append("<option value='" + style.StyleID + "'>" + style.Description + "</option>");
}
build.Append("</select>");
if(Request.QueryString["style"] != "")
{
var choosen = Request.QueryString["style"];
var tbl_colour = (from c in db.tblfsk_style_colour where c.StyleID == choosen select c).ToArray();
build.Append("<select id='colour' name='colour' class='styles'>");
foreach (var colour in tbl_colour)
{
build.Append("<option value='" + colour.ColourID + "'>" + colour.ColourID + "</option>");
}
build.Append("</select>");
}
build.Append("<button type='submit' class='btn'>Continue</button>");
The idea is when they choose Continue as a Button the next thing loads up but I am struggling to find a way to check if the style is null or not.
I have tried:
if(Request.QueryString["style"] != "") { // next <select> tag
And:
if(!string.IsNullOrEmpty(Request.QueryString["style"])) { // next <select> tag
Is there a way to determine if the style is null in the GET?
PHP example of doing this (to explain better):
if(isset($_GET['style'])) { // next <select> tag

I fixed this by trying using the try and catch method.
try
{
var sty_in = Request.QueryString["style"].ToString();
build.Append("test");
}
catch(Exception)
{
var tbl_st = (from c in db.tblfsk_style select c).ToArray();
build.Append("<select id='style' name='style' class='styles'>");
foreach (var style in tbl_st)
{
build.Append("<option value='" + style.StyleID + "'>" + style.Description + "</option>");
}
build.Append("</select>");
}
So if it has been inputted, we can replace test with putting our new <select> statement.
Or even easier:
if(!string.IsNullOrEmpty(Request.QueryString["style"].ToString())){ }
Or
if(Request.QueryString["style"].ToString() != null) { }
I was missing the ToString()

You are using Request.QueryString so the value should be passed through the URL as a GET parameter. You can easily see the value of style if it is passed correctly through the URL string.

Related

jquery ASP.Net "Invalid expression term '{'"

I am using jQuery in ASP.Net mvc 5 website project.
This is my code
function loadTableWorkshops() {
#foreach (var item in Model) {
var row = jQuery("<tr></tr>").append("<td>" + item.title + "</td><td>" + item.date + "</td>");
var deletebtn = jQuery("<a>Delete</a>").attr({
"data-toggle": "modal",
"data-target": "#myModal"})
.addClass("delete")
.click(function () { displayDeleteAlert(item.wid, item.title) });
var detailsbtn = jQuery("<a>Details</a>").attr("href", "/TLCWS/myPlutonLocalhost/workshopDetails.php?wid=" + item.wid + "&wstitle=" + item.title)
.addClass("details");
...
} //foreach
} //function
the error that I receive is
CS1525: Invalid expression term '{'
and it references this line of code
var deletebtn = jQuery("<a>Delete</a>").attr({
I tried to initialize the var deletebtn in one line but the problem is still there. I am sure that jQuery is included properly in my project since it works fine in other places of the project and in the same file too.
When you use #foreach .. { the following statements are c# statements until the closing } - but you've put javascript/jquery statements there instead.
Without checking, you should be able to do:
function loadTableWorkshops() {
#foreach (var item in Model) {
// item is server-side so needs #item
<text>
var row = jQuery("<tr></tr>").append("<td>" + #item.title + "</td><td>" + #item.date + "</td>");
var deletebtn = jQuery("<a>Delete</a>").attr({
"data-toggle": "modal",
"data-target": "#myModal"})
.addClass("delete")
.click(function () { displayDeleteAlert(#item.wid, #item.title) });
var detailsbtn = jQuery("<a>Details</a>").attr("href", "/TLCWS/myPlutonLocalhost/workshopDetails.php?wid=" + #item.wid + "&wstitle=" + #item.title)
.addClass("details");
...
</text>
} //foreach
}
but you might want to completely rethink how you are generating your dynamic html.
For example, you could convert your model to javascript first, then use pure js to manipulate it, eg:
function loadTableWorkshops() {
var items = '#Model.ToString()'; // convert here, maybe use JSON if you haven't overridden ToString()
items.each(function() {
var item = this;
var row = jQuery("<tr></tr>").append("<td>" + item.title + "</td><td>" + item.date + "</td>");
var deletebtn = jQuery("<a>Delete</a>").attr({
"data-toggle": "modal",
"data-target": "#myModal"})
.addClass("delete")
.click(function () { displayDeleteAlert(item.wid, item.title) });
var detailsbtn = jQuery("<a>Details</a>").attr("href", "/TLCWS/myPlutonLocalhost/workshopDetails.php?wid=" + item.wid + "&wstitle=" + item.title)
.addClass("details");
...
} //each
}
The key will be in how you convert Model to items - it's unlikely ToString will suffice, but should get you closer.

How do I check whether an item exists in Listbox in asp.net?

How do I check whether an item already exists in a Listbox?
I am using VS 2008 ASP.NET 3.5 framework C#. I used the following code...
if (ListBox1.Items.Contains(drp_branch.SelectedItem.Value + "-" + txt_acc_no.Text))
{...}
Try this...
string toMatch = drp_branch.SelectedItem.Value + "-" + txt_acc_no.Text;
ListItem item = ListBox1.Items.FindByText(toMatch);
if (item != null)
{
//found
}
else
{
//not found
}
you can use this for checking if item is exsits in list box or not ...
string checkitem = drp_branch.SelectedItem.Value + "-" + txt_acc_no.Text;
if ((ListBox1.Items.Contains(checkitem) == true))
{
Response.Write("Item exists");
}
else
{
Response.Write("Item not exists");
}

Creating jquery object array and posting its values on form submit

I have dynamicly added html elements(selectlists) in a form :
//Dynamicly adding selectlist elements
function newshit() {
i = i + 1
$("#mytable").append("<tr><td><div id='div" + i + "'><select id='elem" + i + "' name='elem" + i + "' class='ted'></select><input type='button' value='-' id='buttonminus" + i + "' style='width:5%;' onclick='removeelem(elem" + i + ",buttonminus" + i + "," + i + ")'/></div></td></tr>")
getitems("elem" + i)
}
//filling lists
function getitems(item) {
$.getJSON('#Url.Content("~/Stok/Items/")', {}, function (data) {
$.each(data, function (i, c) {
$("#" + item).append("<option value='" + c.Value + "' title='" + c.Text + "' label='" + c.Text + "'>" + c.Text + "</option>")
})
})
}
//removing element, when button next to it used
function removeelem(elem,buttonminus,i) {
if ($("select").length > 1) {
$("#div" + i).closest('tr').empty().remove()
} else if ($("select").length <= 1) {
alert("At least 1 of items must be chosen to create a group!")
}
}
//checking elements and values existence
function check() {
var slcts = $("select").serialize();
alert(slcts)
}
im trying to get the value of each selectlist's selected option value and put them into an array than send them to my controller on form submit.
How can i achive this?
Need to check this, but I think that the following should work:
Change your code so that the format of your ids is something like:
id="elem[0]"
Then if your controller has a signature something like this:
public ActionResult Something(IEnumerable<string> elem)
{
}
Then his should "just work".
You could use something like -
var selectdata = $("select").serialize()
This will return a string in the form <select name attribute1>=<chosen value1>&<select name attribute2>=<chosen value2> etc. You'd need to add a 'name' attribute to your select HTML when you create it for this to work.
Demo - http://jsfiddle.net/ipr101/fZXha/
You could then put the selectdata variable in a hidden field before the form was posted or send it via AJAX using the ajax or post methods.

error: The query results cannot be enumerated more than once

Edit:
DataClassesDataContext dc = new DataClassesDataContext();
string _idCompany = Request["idCompany"];
var newes = dc.GetNewsCompany(Int64.Parse(_idCompany));
string date = "";
string newsHtml = "<center>";
if(newes.GetEnumerator().MoveNext()){
foreach (var item in newes)//say Error .......................
{
// date = calendar.GetDayOfMonth(item.DateSend) + "/" + calendar.GetMonth(item.DateSend) + "/" + calendar.GetYear(item.DateSend).ToString();
// newsHtml += "<li class='news-item'><a style='text-decoration:none' class=\"link\" onclick=\"$(\'#BodyNews\').text(\'" + HttpUtility.HtmlEncode(item.Body).Trim() + "\');$(\'#BodyNews\').dialog({resizable:false});\" href=\"#\" > " + item.Title.ToString() + "</a> " + date + " </li>";
}
newsHtml += "</center>";
}
else
{
// var propertyCompany = dc.GetPropertyCompanyById(Int64.Parse(_idCompany));
// newsHtml += "<li class='news-item'><a style='text-decoration:none' class=\"link\" );$(\'#BodyNews\').dialog({resizable:false});\" href=\"#\" > " + "!به صفحه شخصی شرکت " + propertyCompany.FirstOrDefault().NameCompany + " خوش آمدید " + "</a> " + date + " </li>";
}
return newsHtml;
say error:The query results cannot be enumerated more than once
how check var is empty or null with out enumerated;
Why bother with the if at all?
var newes = dc.GetNewsCompany(Int64.Parse(_idCompany));
//if (newes.GetEnumerator().MoveNext())//check is null or empty
var newesList = newes.ToList();
if (neweList.Count > 0)
{
...
}
You can always check the newesList.Count property afterward.
Not sure what's available as a member in newes, but if it's an object and depending on what dc.GetNewsCompany returns you could check for null
if (news == null) return;
or if it returns an empty collection/array, just check the count/length:
if (news.Count == 0) return;
if (news.Length == 0) return;
the error comes, because you are using .GetEnumerator() on newes and then using the newes again in a foreach Loop .. this causes the "double enumeration".
Generally avoid walking "such var"'s with a foreach, since the DataReader is locked the whole loop !. Means that you cannot use the same entitie in this loop.
Better .ToList() , you can the list.AsQuearable agian if you want to Linq on it
f.e. something like
var newes = dc.CompanyTable.Where(ln => ln.id.Equals(_idCompany));;
List<CompanyTable> newesList = newes.ToList();

get the ancestor nodes of a selected xml node using c# into a multiline text box

Im using c#.net. I have an xml file that contains many nodes. I have got the xml file into a tree view. Now when I select a particular node in the treeview, I should be able to display all its ancestors in a multiline text box. Please suggest me to do this job.
I´m not really sure what you want but this might be some thing to start with.
The extension method will get the xpath to an XElement node with attributes to specify the exact element more precisely.
public static string ToXPath(this XElement element)
{
var current = element.Parent;
string result = "";
while (current != null)
{
string currentDef = current.Name.ToString();
string attribsDef = "";
foreach (var attrib in current.Attributes())
{
attribsDef += " and #" + attrib.Name + "='" + attrib.Value + "'";
}
if (attribsDef.Length > 0)
{
currentDef += "[" + attribsDef.Substring(5) + "]";
}
result = "/" + currentDef + result;
current = current.Parent;
}
return result.Substring(1);
}

Categories