String contents change while pasing from view to controller Get method - c#

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.

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)

How does FromQueryAttribute actually work and why do I need it?

I'm working with some pre-existing code that uses an HttpGet endpoint to get all comments. It takes some default parameters and before each parameter it is decorated with a [FromQuery] attribute. I'm a little confused about why we need this here and what it really does for me.
There isn't much online all I found was this documentation:
(https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.fromqueryattribute?view=aspnetcore-2.2)
This doesn't answer my question though...
What is a query string?
How is it used in endpoints?
When is it that I don't need to specify this attribute? I don't see it being used very much.
[HttpGet]
[ProducesResponseType(typeof(FooResponse), 200),
public async Task<ActionResult<FooResponse>> GetAll([FromQuery]string sortColumn = "CommentId",
[FromQuery]SortDirections sortDirection = SortDirections.Asc,
[FromQuery]string filter = "",
[FromQuery]int page = 1,
[FromQuery]int pageSize = 10)
{
var data = await _mediator.Send(new GetAllComments(sortColumn, sortDirection, filter, page, pageSize));
.
.
.
return Ok(data);
}
I suspect that it has something to do with what is passed into the URL but I'm not quite sure...
The usage here is superfluous. The action would function the same without [FromQuery] being applied to all the params, as it only responds to GET requests.
What is a query string?
The query string is the portion of the URI after the ? character is applied. It constitutes a data portion of a URI versus a pure routing portion.
How is it used in endpoints?
The question here is a little tenuous, so it would be more appropriate to ask "How is it used in a request?" The answer to that it is a way to pass data along with a GET request to a particular URI. Unlike other HTTP methods, GET does not really allow a request "body". (Actually, the spec technically does allow this, but it's almost universally not implemented that way.)
When is it that I don't need to specify this attribute? I don't see it being used very much.
Again, a better question is "When do I actually need to specify this attribute?" The answer to that is basically when it's ambiguous where the data is coming from. This will almost invariably be with other HTTP methods such as POST. By default, data is expected to come from the request body there, and depending on the content type of that request body, the binding is expected to be either FromForm or FromBody, which will usually be the default for params there. (Which is the default depends on whether you're dealing with a traditional MVC-style controller or an API-style controller.) If you need to actually get a particular param from the query string instead of the body in such a scenario, then you would apply the [FromQuery] attribute to that particular param.
Since the action in your post is for GET requests only ([HttpGet]) the [FromQuery] isn't necessary - the parameters will automatically use the associated query string values.
For POST actions ([HttpPost]) this attribute specifies to grab the value from the query string as opposed to the data which was posted.
Query string is a part of the URL that comes after an ? and it provides a way to pass values as a list of key-value pairs, each pair separated by & characters. Say you have the following URL:
http://mywebsite.com/somePage?a=123&b=Hello&c=World
So the query string part int that URL corresponds to a=123&b=Hello&c=World, and the list of key-value pairs that were passed was:
a = 123
b = Hello
c = World
ASP.NET Core can bind values to variables in a lot of different ways, and one of them is by reading values from a query string and converting/assigning these values to the values of your API's methods. To specify that a parameter should come from the query string, you use the [FromQuery] attribute.
So - for instance - when you have [FromQuery]string sortColumn = "CommentId" you are basically telling it to read the sortColumn key from the query string and assign it to the sortColumn parameter of the GetAll() method, and if that "sortColumn" key is not present in the query string, it should be assigned the default "CommentId" value. It is similar to the other parameters.
So you could access that URL with something like that (you should use the correct URL to get to your GetAll method, which I can't tell with the code you have provided):
http://your-system-url-here/GetAll?page=2&pageSize=20
Which would assing the page parameter a value of 2 and the pageSize parameter a size of 20.

How to send local variables via post

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.

how does Request.QueryString work?

I have a code example like this :
location.href = location.href + "/Edit?pID=" + hTable.getObj().ID; ; //aspx
parID = Request.QueryString["pID"]; //c#
it works, my question is - how ? what is the logic ?
thanks :)
The HttpRequest class represents the request made to the server and has various properties associated with it, such as QueryString.
The ASP.NET run-time parses a request to the server and populates this information for you.
Read HttpRequest Properties for a list of all the potential properties that get populated on you behalf by ASP.NET.
Note: not all properties will be populated, for instance if your request has no query string, then the QueryString will be null/empty. So you should check to see if what you expect to be in the query string is actually there before using it like this:
if (!String.IsNullOrEmpty(Request.QueryString["pID"]))
{
// Query string value is there so now use it
int thePID = Convert.ToInt32(Request.QueryString["pID"]);
}
A query string is an array of parameters sent to a web page.
This url: http://page.asp?x=1&y=hello
Request.QueryString[0] is the same as
Request.QueryString["x"] and holds a string value "1"
Request.QueryString[1] is the same as
Request.QueryString["y"] and holds a string value "hello"
The Request object is the entire request sent out to some server. This object comes with a QueryString dictionary that is everything after '?' in the URL.
Not sure exactly what you were looking for in an answer, but check out http://en.wikipedia.org/wiki/Query_string
Request.QueryString["pID"];
Here Request is a object that retrieves the values that the client browser passed to the server during an HTTP request and QueryString is a collection is used to retrieve the variable values in the HTTP query string.
READ MORE#
http://msdn.microsoft.com/en-us/library/ms524784(v=vs.90).aspx
The QueryString collection is used to retrieve the variable values in the HTTP query string.
The HTTP query string is specified by the values following the question mark (?), like this:
Link with a query string
The line above generates a variable named txt with the value "this is a query string test".
Query strings are also generated by form submission, or by a user typing a query into the address bar of the browser.
And see this sample : http://www.codeproject.com/Articles/5876/Passing-variables-between-pages-using-QueryString
refer this : http://www.dotnetperls.com/querystring
you can collect More details in google .

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