How to send local variables via post - c#

Via a hidden input field I want to send a value from Site 1 to Site 2.
But at Site 2 it says the value is null.
I guess this is because it is local value. But it has to be local and I'm not sure.
Here is my code where I declare the value (page 1):
string stringproductid = Request.QueryString["id"].tostring();
int productid = stringproductid.AsInt();
Here I send it via a hidden field inside a form (page 1):
<input type="hidden" id="#productid" value="#productid" name="#productid">
Here I try to receive it (at page 2):
string idstring = Request.Form["productid"].ToString(); //error

It should be name="productid" . The # you're using there is making Razor put the value of productID into that attribute. So if you look at your raw generated HTML it is going to be something like name="346".
That belongs in the "value" attribute, which you did correctly, but what you need to be putting in the "name" is the name of the field, so that the browser posts it back correctly with that field name. :-)

On your 2nd page, you should use
string idstring = Request.Form["#productid"].ToString(); //error
On a side note, both Request.QueryString[] and Request.Form[] are always strings, so you don't need to include the .ToString(). I understand it may be defensive coding, but you are just adding CPU cycles. They add up over time.

Related

Using Replace within html actionlink

I have an application in MVC5/C#
My index view is a simple list from a model. I added an additional html actionlink to view the history of any selected item. With this link, I am going to a different controller (ICS_HistoryView) and passing an id parameter.
Originally it broke because some of the items (Old_ItemID field) have / in them, causing the link to break. So, after some research, I learned that I can use Replace to replace / with -, so the url will not break and then switch it back in the controller of the new view. However, I am getting a null error when the view loads, on this line
#Html.ActionLink("History", "History", "ICS_HistoryView", new { id = item.Old_ItemID.Replace('/', '-')}, null)
But, without the Replace, it loads properly. Only when I click the History link, does the url break with the / in the parameter.
#Html.ActionLink("History", "History", "ICS_HistoryView", new { id = item.Old_ItemID}, null)
Can someone help me understand why it becomes null when I use replace and breaks the code?
I can provide the controller code if needed, but it's really simple. This is just a list view.
Example:
Old_ItemID = VNC/2/1
Without the Replace, I get the correct url with parameter VNC/2/1 but I get page not found, obviousl
Adding Replace, I get a null error - and I don't understand why
The only reason I suspect for this error is when item.Old_ItemID is null.
Otherwise it works fine for string with any value including empty string.
Could you try adding null-condition operator like item.Old_ItemID?.Replace("/","-")
For best practice, I would suggest such manipulations in Model/Domain classes.
Create a Get property or a method in Item (or whatever class that is) to replace tokens in URL.
i.e.
public string OldItemIdForUrlGeneration => this.Old_ItemID.Replace("/", "-");
and then
#Html.ActionLink("History", "History", "ICS_HistoryView", new { id = item.OldItemIdForUrlGeneration }, null)

String contents change while pasing from view to controller Get method

In MVC application, I am passing string taskName = "a#&+" from UI text box.
In the controller, parameter taskName changes to taskName = "a".
On debugging the view, the value of taskName is displayed as expected.
But while passing from view to controller, it changes unexpectedly.
Post method is then posting same incorrect string back to UI. How to obtain taskName = "a#&+" in the controller GET method?
I am new to MVC. Please let me know, if I can provide further relevant information.
I am not exactly sure how you are passing data from a text box on the page to the controller parameter but based on your description it appears that you must be using javascript to get the value of the text box and then attaching it to the url. In this case you need to encode the value of the of the text box before using it by using the javascript encodeURIComponent function.
See this jsfiddle for an example: http://jsfiddle.net/a7ek6whn/
The characters # and & are reserved characters in a query string, this is why your value is truncated. You need to UrlEncode your values in order to get the correct string in the Get, before you perform your Get request.

Parsing HTML Input to C# code on Page Load

I have a tricky question. Hope somebody can answer this for me.
I am using a Site based on DOtnetNuke CMS. I have a page which has an input field
<input name="ct100$dynamicinputfield1" id=ct100$dynamicinputfield1 value="abc">
This input field is auto generated and i cannot change the code for this.
Now i have another module which runs on Page_load
The module has A stored Procedure which expects an input parameter which is the value of the Input field mentioned above.
I supply the parameter to the code using this line
string Id = Request.Form["ctl00$dynamicinputfield1"];
I get the following Error
Error:System.Data.SqlClient.SqlException (0x80131904): Procedure or
function 'GetAddressByID' expects parameter '#ID', which was not
supplied.
I believe this happens because the Server side code executes before the client side. and thus the Request.form cannot find the dynamicinputfield1. How can i solve this Issue.
After posting the form from client side you must have to get this property value.
Before posting the form how can u get one.
second thing you must get the value of the item on server side before posting to client with the original name of the input field.
hope this answer helps.

Can I pass a .net Object via querystring?

I stucked at a condition , where i need to share values between the pages. I want to share value from Codebehind via little or no javascript. I already have a question here on SO , but using JS. Still did'nt got any result so another approach i am asking.
So I want to know can i pass any .net object in query string. SO that i can unbox it on other end conveniently.
Update
Or is there any JavaScript approach, by passing it to windows modal dialog. or something like that.
What I am doing
What i was doing is that on my parent page load. I am extracting the properties from my class that has values fetched from db. and put it in a Session["mySession"]. Some thing like this.
Session["mySession"] = myClass.myStatus which is List<int>;
Now on one my event that checkbox click event from client side, i am opening a popup. and on its page load, extracting the list and filling the checkbox list on the child page.
Now from here user can modify its selection and close this page. Close is done via a button called save , on which i am iterating through the checked items and again sending it in Session["mySession"].
But the problem is here , when ever i again click on radio button to view the updated values , it displays the previous one. That is , If my total count of list is 3 from the db, and after modification it is 1. After reopening it still displays 3 instead of 1.
Yes, you could but you would have to serialize that value so that it could be encoded as a string. I think a much better approach would be to put the object in session rather than on the URL.
I would so something like this.
var stringNumbers = intNumbers.Select(i => i.ToString()).ToArray();
var qsValue = string.Join(",", stringNumbers);
Request.Redirect("Page.aspx?numbers=" + sqValue);
Keep in mind that if there are too many numbers the query string is not the best option. Also remember that anyone can see the query string so if this data needs to be secure do not use the query string. Keep in mind the suggestions of other posters.
Note
If you are using .NET 4 you can simplify the above code:
var qsValue = string.Join(",", intNumbers);
Make the object serializable and store it in an out-of-process session.
All pages on your web application will then be able to access the object.
you could serialize it and make it printable but you shouldn't
really, you shouldn't
The specification does not dictate a minimum or maximum URL length, but implementation varies by browser and version. For example, Internet Explorer does not support URLs that have more than 2083 characters.[6][7] There is no limit on the number of parameters in a URL; only the raw (as opposed to URL encoded) character length of the URL matters. Web servers may also impose limits on the length of the query string, depending on how the URL and query string is stored. If the URL is too long, the web server fails with the 414 Request-URI Too Long HTTP status code.
I would probably use a cookie to store the object.

How to get the value

Using C# & Java Script
I have the link like this
"http://localhost/Server/Vehicle/Vehicle.aspx?appid=5", when i use this link the page is opening... But i want to get this appid value, then pass this appid value to another link
In the above link appid value is 5
For Example
Link1 http://localhost/Server/Vehicle/Vehicle.aspx?appid=5
In link2 the value 5 should display like this "http://localhost/Server/Vehicle/car.aspx?appid=5"
Tried Code
Entry
But in another page the link is displaying like this
http://localhost/Server/Vehicle/car.aspx?param=document.getElementById('appid').value
How to get that appid value. I want to pass this value to another link
Need code Help
Access the Request.QueryString as follows to retrieve the value of the appid query variable:
string appid = Request.QueryString["appid"];
Update:
The JavaScript snippet won't be executed in the href attribute of a link (it's recognized as a normal string, and won't be parsed as JavaScript code).
With the following link a user will be successfully directed to your desired URL:
Entry
Side note: the value property works only for HTML tags that have defined an eponymous attribute. One such tag would be the input tag. The div tag instead doesn't have a value attribute defined, and therefore document.getElementById('appid').value would fail; use innerHTML instead in that case.
You can try using
string appID;
if(Request.QueryString["appid"] != null)
{
appID = Request.QueryString.Get("appid");
}

Categories

Resources