Expression for asp-route-{value} - asp.net-core

asp-route-date="#{ DateTimeOffset.Parse(date); }"
Should that work? Can't find any info. Currently that somehow give me pure date variable value, f.e. - ...?date=01%2F02%2F2020+4%3A49+PM

Use Razor expressions instead Razor code blocks so that the value will be rendered in the resulting HTML, e.g.:
Razor:
<a asp-action="CheckDate" asp-route-date="#DateTimeOffset.Parse(date)">check</a>
Controller:
public ActionResult CheckDate(DateTimeOffset date)
{
// ...
}
The query string in your example seems fine, as the DateTimeOffset object needs to be encoded to be passed to the controller. For alternative formats and further information see How do I pass a datetime value as a URI parameter in asp.net mvc?.

Related

RazorPages anchor tag helper with multiple parameters

Here's the RazorPages page I'm trying to make a link to:
#page "{ReportId:int}/{SicCode:alpha?}"
This works
<a asp-page="/ReportSics" asp-route-ReportId="3">rs1</a>
it produces
rs1
But this produces a blank href.
<a asp-page="/ReportSics" asp-route-ReportId="3" asp-route-SicCode="10">rss2</a>
That is: the tag helper works with one parameter but not with two.
Why?
Is it possible to make it work?
(I have another page with the same #page but with the second parameter not optional and it appears to be impossible to create a link to it.)
Furthermore, requesting Page/2/M works, but Page/2/12 returns 404. Why? (The second parameter is a string that can sometimes be a number, but it always treated as a string.)
From the learn.microsoft.com webpage asp-all-route-data offers the following:
asp-all-route-data
The asp-all-route-data attribute supports the creation of a dictionary of key-value pairs. The key is the parameter name, and the value is the parameter value.
In the following example, a dictionary is initialized and passed to a Razor view. Alternatively, the data could be passed in with your model.
#{
var parms = new Dictionary<string, string>
{
{ "speakerId", "11" },
{ "currentYear", "true" }
};
}
<a asp-route="speakerevalscurrent"
asp-all-route-data="parms">Speaker Evaluations</a>
The preceding code generates the following HTML:
Speaker Evaluations
Extension: From here the parameters can be accessed either explicitly in the parameter list of the method:
public IActionResult EvaluationCurrent(int speakerId, string currentYear)
or as a collection (See response: queryString:
public IActionResult EvaluationCurrent()
{
var queryString = this.Request.Query;
}
This works
Yes it works because it produces a route that is similar to this baseUrl/reportsics/?reportId=5
And the other produces a URL that is similar to this baseUrl/reportsics/?reportId=5&sicCode=678 and then it doesn't match your route definition. I think you should try this.
Experimental
asp-page="/reportSics/#myId/#sicCode
Though this would not be the right way to do what you're thinking. If you really want to change your URL structure, why not do url-rewrite?
Edit.
Form your recent comments, seems you want to pass many parameters in your action method and not targeting URL structure. Then I recommend you just
public IActionResult(string ReportId, string sicCode)
{
//......
}
//And the your URL target
<a asp-page="ReportSics" asp-route-ReportId="55" asp-route-sicCode="566" ></a>
And then it will match the route. I think you should remove that helper you placed after your #page definition and try it out if this is what you have already done and the problem persists.
It turns out that if a parameter has the constraint :alpha then it only works if the value being passed can not be parsed as an int or float.

Get Query String Value in ASP.NET MVC Function

I have an ASP.NET MVC app. My views use Razor. At the top of my CSHTML file, I have the following:
#functions
{
public static HtmlString IsSelectedCss(string name)
{
string selected = ""; // Need to get value of "t" from query string
HtmlString attribute = new HtmlString("");
if (selectedTab.Equals(name, StringComparison.InvariantCultureIgnoreCase))
{
attribute = new HtmlString("class=\"active\"");
}
return attribute;
}
}
I need this function to examine the query string. Specifically, I need to get the value of the "t" query string parameter. My challenge is, I cannot seem to figure out how to get access to the QueryString in this function.
How do I get the value of a query string parameter in a Razor function?
Thanks!
The query string can be gotten from below.
HttpContext.Current.Request.QueryString["t"]
You need to make your function non-static, since the querystring is part of the request.
You can then write
HttpContext.Request.Query["t"]
You should really be doing this in the controller and pushing it through the model. But if you insist, you can simply use:
<%= Request["t"] %>
But why not read it in your controller?!

how to remove validate input parameters on a action?

i want to redirect from on page to another on mvc and pass some parameter and get them on second page.
my parameter is something like this
?id=UXodaA54Iqo+gId3avkIqA
but when i get this parameter on the second the page some characters like "+" removed
and the parameter has been changed to this
UXodaA54Iqo gId3avkIqA
my action is
[ValidateInput(false)]
public ActionResult test(string id)
{
return view();
}
what is the best way to handle it just for this action because i do not want to put some thing like this on my web config
<httpRuntime requestValidationMode="2.0" />
This is not releated to validation. A + character in a query string parameter is seen as a space. Use HttpUtility.UrlPathEncode() to encode your parameter.

IN MVC 4 how do you pass data to your controller without using the query string

We have a form that displays user information for a list of users. We have an action link to go to a details view for the user to update information. Our application is a mixture of ASP.Net 4.0 and MVC. We normally use encryption to mask variables we use in the query string, but MVC chokes when we attempt to encrypt the query string. We are using the Microsoft Enterprise 5.0 Cryptogrophy class.
How would we go about either encrypting the query string or passing the data without using the query string at all?
We are using MVC 4 with Razor.
We are currently doing something like this:
#Url.Action("Edit", "User", new {id = user.Id}
BTW, I am new to MVC, so there may be an easy answer to this that I am just not aware of.
It would be really nice if we could not use the query string at all.
The simple answer: POST. Use a form or an AJAX call to send the values as POST data, and have a controller method named the same as the existing one, but marked with the [HttpPost] attribute (also, mark the existing one as [HttpGet]). The arguments for this new POST method can be whatever you like; they may get turned into strings when they get POSTed (especially if you use AJAX) but MVC is smart enough to convert them back again provided they're named the same. So, a form that's something like this:
#using (Html.BeginForm("Edit", "User", FormMethod.Post, new { id = "mainForm" }))
{
<input id="userId" type="text" />
<input type="submit" />
}
will correspond neatly to a controller method like this:
[HttpPost]
public ActionResult Edit(int userId)
{
//do whatever
}
provided you've got the routes registered properly. If your GET method is working, then the same route will work here, as long as it doesn't do anything problematic with URL parameters.
That same method will also accept the submission from an AJAX call that looks something like this:
$.ajax({
type: "POST",
url: '#Url.Action("Edit", "User")',
data: { userId: #user.Id },
success: function (data) {
//do whatever
}
});
I agree with anaximander, but if you're going to that much effort to secure the query string information, forms just move the information to HTML fields instead of query string parameters. If you need to keep your existing implementation you could look into inheriting from the default ModelBinder, and provid your own custom implementation to convert from encrypted query string to unencrypted query string before you hand it over to the base class's implementation.

JSON result problems in ASP.NET Web API when returning value types?

I'm learning aspnet mvc 4 web api, and find it very easy to implement by simply returning the object in the apicontrollers.
However, when I try to return value types such as bool, int, string - it does not return in JSON format at all. (in Fiddler it showed 'true/false' result in raw and webview but no content in JSON at all.
Anyone can help me on this?
Thanks.
Some sample code for the TestApiController:
public bool IsAuthenticated(string username)
{
return false;
}
Some sample code for the jQuery usage:
function isAuthenticated(string username){
$.getJSON(OEliteAPIs.ApiUrl + "/api/membership/isauthenticated?username="+username,
function (data) {
alert(data);
if (data)
return true;
else
return false;
});
}
NOTE: the jquery above returns nothing because EMPTY content was returned - however if you check it in fiddler you can actually see "false" being returned in the webview.
cheers.
Before your callback function is called, the return data is passed to the jquery parseJSON method, which expects the data to be in the JSON format. jQuery will ignore the response data and return null if the response is not formatted correctly. You have two options, wrap you return boolean in a class or anonymous type so that web api will return a JSON object:
return new { isAuthentication = result }
or don't use getJSON from jQuery since you're not returning a properly formatted JSON response. Maybe just use $.get instead.
Below is a quote for the jQuery documentation:
Important: As of jQuery 1.4, if the JSON file contains a syntax error,
the request will usually fail silently. Avoid frequent hand-editing of
JSON data for this reason. JSON is a data-interchange format with
syntax rules that are stricter than those of JavaScript's object
literal notation. For example, all strings represented in JSON,
whether they are properties or values, must be enclosed in
double-quotes. For details on the JSON format, see http://json.org/.