I have made a link on the webpage like
<a href="Products.aspx?id='something'">
Now this send id to a page Products.aspx
I want this value of id in the Products.aspx.cs file of the page so that I can write a query like
select * from Categories Where CategoryID = 'something'
Try to use the following ,Below i mentioned get Querystring value in code behind.
string Id = string.Empty;
if (Request.QueryString["id"] != null)
{
Id = Request.QueryString["id"].ToString();
}
var query = " select* from Categories Where CategoryID = '" + Id + "'";
You can get id sent using Query String like below:
if(Request.QueryString["id"] != null)
{
string value = Request.QueryString["id"].ToString();
}
You have lots of way to pass id Form One Page to Another page Name
Products.aspx Or Products.aspx.cs
Ill Explain Two way
One is Session and Another is QueryString.
Session Examle.............
Session : Assign Value of ID on Page A
Session["id"]='something';
Get Value On Page Products.aspx
string Val=Session["id"].ToString();
Query String Examle.............
QueryString: Assign Value of ID on Page A
string DymanicURL = string.Format("Products.aspx?id={0}", Val);
Response.Redirect(DymanicURL);
Get Value On Page Products.aspx
string x = Request.QueryString["id"];
For More Info http://www.dotnetperls.com/querystring
and https://msdn.microsoft.com/en-us/library/6c3yckfw.aspx
you can get the ID value in the targeted products cs page using following syntax
string ID = Request.QueryString["id"].tostring();
You can get query string values as passed in the way you describe using
var categoryId = Request.QueryString["CategoryId"]
You'll want to check that it's not null or empty before proceeding, of course...
Try to use the following
string Qvalue="";
if(Request.QueryString["id"] != null) {
Qvalue = Request.QueryString["id"].ToString(); }
Your query should look likes this
select * from Categories Where CategoryID = '"+Qvalue+"'
if you would like to send id from one page to another CS page then you may use properties
class Person
{
private string name; // the name field
public string Name // the Name property
{
get
{
return name;
}
set
{
name = value;
}
}
}
On ASPX Page you may put value on properties like :
Person person = new Person();
person.Name = "Joe"; // the set accessor is invoked here
OR
person.Name = txt_Name.Text; // the set accessor is invoked here
after that get data On CS page.
System.Console.Write(person.Name); // the get accessor is invoked here
OR
string Value= person.Name; // the get accessor is invoked here
Related
I have a viewmodel to update data (from API, not view) with params like below:
public string Name { get; set; }
public string Email { get; set; }
public string Phone { get; set; }
i just want to update "name", so my param like below:
{
"name": "my name"
}
its name changed become "my name" but its email and phone become null. how to avoid params changed to be null if they don't exist in input form?
Thanks...
You'll have to adjust whatever does the update so that it understands "null means do not set a value, rather than set the value to null"
For example if you're running a db update query you could:
UPDATE person
SET
name = COALESCE(#name, name),
email = COALESCE(#email, email),
phone = COALESCE(#phone, phone)
WHERE
id = #id
Now if any value is supplied as null the update will set the column to the same value it is currently (ie no-op)
If you're adjusting a c# object you can take a similar approach:
var p = db.FindPerson(viewmodel.PersonId);
p.Name = viewmodel.Name ?? p.Name;
...
As I see, you have a problem or misunderstanding in your software design.
If this API endpoint is meant to just update the name field, then you should not have the other fields in your ViewModel. However, if you update the other fields in some cases, then you should pass their values as well.
So maybe you need to call a Get endpoint first to get the all data you need in your client "web page for example" and then allow this client to resend the full JSON, not just the name.
Or you may just need an endpoint that just takes the name.
Another solution, in case you're using EF, is to ignore the null fields when updating the EF entity.
e.g.
...
var entity = dbContext.Employees.FirstOrDefault(e => e.Id == 3);
entity.Name = request.Name;
await dbContext.SaveChangesAsync();
...
Please tell me how to add multiple properties inside an single object.
like- if there is a class having 5 variables defined with get and set.
I want to add like 2 values for each variable through a single object of that class like
class Info{
int count{get , set,};
string name{get , set,};
string Dept {get , set,};
string Address {get , set,};
long contact {get , set,};
info obj =new Info();
/* Now after this I want to take 2 rows like
in first row I want to set it's values through a single object
Count=1,name="Robert",Dept="Computer",Address="India",Contact=434343
in row 2nd row
Count=1,name="Robbin",Dept="Electronic",Address="Colombo",Contact=54545
*/
}
/// Now please explain me how to set like above two rows values inside one object.. ///
I think what you're looking for is inline object initialization: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/how-to-initialize-objects-by-using-an-object-initializer
You can write it on a single line but the code would look better if you break it into multiple lines:
Info infoObj = new Info
{
Count = 1,
Name = "Robert",
Dept = "Computer",
Address = "India",
Contact = 434343
};
If what you mean is initializing a class with set properties, look at Peter Sandor's answer.
if you're looking to declare a class with a set of fields that'll be filled with values upon initialization without giving them values (aka. default values), then this might help:
class Info
{
public int count = 5;
pubic string name = "Robert"
}
Please note that these are fields and not properties though, if you'd like to do the same with properties instead of fields, i'd suggest doing this with propfull:
private int count = 5;
public int Count
{
get { return count; }
set { count = value; }
}
Hope this helps!
Instead of creating an instance of the Info class, make a List of Info:
List<Info> aSingleObj = new List<Info>();
Now you can add as many things to the single object:
aSingleObj.add(new Info { Count = 1, name = "Robert", Dept = "Computer", Address = "India", contact = "434343" });
aSingleObj.add(new Info { Count = 1, name = "Robbin", Dept = "Electronic", Address = "Colombo", contact = "54545" });
To distinguish between them, and print the output, do:
Console.WriteLine($"First row: Count = {aSingleObj[0].Count}, Name = {aSingleObj[0].name}, Department: {aSingleObj[0].Dept}, Address = {aSingleObj[0].Address}, Contact = {aSingleObj[0].contact}");
and for second row:
Console.WriteLine($"Second row: Count = {aSingleObj[1].Count}, Name = {aSingleObj[1].name}, Department: {aSingleObj[1].Dept}, Address = {aSingleObj[1].Address}, Contact = {aSingleObj[1].contact}");
I have just changed my code so that now it stores some data in an enum instead of in a SQL Server table.
Here's the enum:
public enum ContentTypes : int
{
Article = 0,
Menu = 1,
ContentBlock = 3
}
I was running the following code:
var contentTypes =
(
from contentType in this._contentTypeService.GetContentTypes()
select new
{
id = contentType.ContentTypeId,
name = contentType.Name
}
);
How can I change this so that instead of taking the data from the content service it just queries the enum to data for contentTypes?
I think what you want is this
var contentTypes =
from value in Enum.GetValues(typeof(ContentTypes)).Cast<int>()
select new
{
id = value,
name = Enum.GetName(typeof(ContentTypes), value)
};
pswg might be right, but I am thinking you want something like this?
Here is code more direct to your question:
select new
{
id = (int)contentType,
name = contentType.ToString()
}
You can get the integer id simply by casting to an int and get the name of it by using its ToString (which may or may not be implicit here)
I am currently using the following script to set this value as a String:
string ID = Request.QueryString["ID"].ToString();
However, I'd now like to store it as an Integer.
How do I do this?
Many thanks for any pointers.
Assuming you don't want to throw a server error on a bad string
int id=0;
if (int.TryParse(Request.QueryString["ID"],out id)) {
.. logic for valid id
} else {
.. logic for invalid id
}
int ID = int.Parse(Request.QueryString["ID"].ToString());
Use either of these:
If you know that you have an ID:
string ID = Request.QueryString["ID"];
int integerId = int.Parse(ID);
or, if the query string may be missing or invalid (never trust query strings....)
string ID = Request.QueryString["ID"];
int integerId;
if (int.TryParse(ID, out integerId))
{
// you have a valid integer ID here.
// process it
}
else
{
// handle missing or invalid ID
}
You could do something like:
int i = Convert.ToInt32(ID);
or
int i;
Int32.TryParse(ID, out i);
BTW Request.QueryString["ID"] is already a string so the following is fine:
string ID = Request.QueryString["ID"];
Try
int ID = int.Parse(Request.QueryString["ID"]);
See How can I convert String to Int?
You can do like this:
string ID = Request.QueryString["ID"].ToString();
int id=int.Parse(ID);
or
int id=Convert.ToInt16(ID);
Always use tryparse for querystring values if you want to convert it to integer even if you never set it to string , because user can change that anytime before sending request (visible in URL).
int id = 0 ;//default value
bool success = int.TryParse(Request.QueryString["ID"],out id))
if (success) {
//write code for default value action
return;
}
//write code for other values.
How do I request querystring using javascript from URL
e.g : http://localhost:1247/portal/alias__MySite/lang__en/tabid__3381/default.aspx
I want to get tabid...
var tabid = '<%= Request.QueryString["tabid"] %> ';
Above code works only in aspx page
but i dont need it, any ideas? thanks
There is now a new api URLSearchParams. Use that in conjunction with window.location.search
var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.get('tabid'));
If your browser does not support URLSearchParams, you can create a custom fallback function:
function getParam(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.search);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
console.log(getParam('tabid'));
Don't know why but I've always found the javascript for querystring data fetching a bit hacky. if you don't need this value on the initial page load then perhaps you could use Request.QueryString in the code and set the value to a hidden field, which your javascript will read from?
Try this, It is working perfectly for me.
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var tabId=getParameterByName("tabid");
I bet there is a server-side rewrite (DotNetNuke?), so the aspx.cs "sees" the redirection target which contains the correct QueryString.
For the client, you have to use another mechanism because the browser only "sees" the public URL. In this case, a Regex that picks the number behind 'tabid_' and before the next slash should work. This would be the same number (page id?) that the aspx page "sees".
This is what I used:
<script type="text/javascript">
function QueryString(key) {
//Get the full querystring
fullQs = window.location.search.substring(1);
//Break it down into an array of name-value pairs
qsParamsArray = fullQs.split("&");
//Loop through each name-value pair and
//return value in there is a match for the given key
for (i=0;i<qsParamsArray.length;i++) {
strKey = qsParamsArray[i].split("=");
if (strKey[0] == key) {
return strKey[1];
}
}
}
//Test the output (Add ?fname=Cheese&lname=Pizza to your URL)
//You can change the variable to whatever it is you need to do for example, you could
//change firstname to id and lastname to userid and just change the reference in the
//document.write/alert box
var firstname = QueryString("fname");
var lastname = QueryString("lname");
document.write("You are now logged in as " + firstname + " " + lastname + "!");
</script>
You can replace document.write with alert and it would give you an alert box instead!
I used this on my website. Its not done yet but when it is it will be at zducttapestuff.com
The output will look like this: You are now logged in as Cheese Pizza!
This is very unsecure for Passwords though since the password will be shown in the url.