Basically my enum value determine's the page your on (in the url)and I have the below "if" statement to cover the stituation , if a user enters a load of text in the url it defaults to "New"......put if I enter any number other then the Enum values it displays that number instead of the default "New" page.
I don't want to post a load of code so hopefully it's clear, it redirects correctly if text entered in URL, but not for non-enum value. Is there a way to check if the Url input matches a enum value ?
ActionResult
[HttpGet]
public ActionResult Index(string status, string message)
{
var referralStatus = ReferralStatus.New;
if (!Enum.TryParse(status, out referralStatus))
{
referralStatus = ReferralStatus.New;
}
var model = new ReferralsModel();
model.Status = referralStatus.ToString();
model.ReferralsCount.Status = referralStatus.ToString();
return View(model);
}
Your url when landing on the Index page reads..
project/Referrals ,
your url after selecting a tab on the page reads...
project/Referrals?Status=2 ,
your url when entering diferent numbers in the Url
project/Refferals?status =56473 ,
your view renders with these numbers in place of enum status value.
please note this is an asp.net mvc 4 application
Edit : As stated in the comments, you may use Enum.IsDefined for parsing int representation of Enum
if (!Enum.TryParse(status, out referralStatus))
should be
if (!Enum.TryParse(status, out referralStatus) || !Enum.IsDefined(typeof(ReferralStatus),referralStatus))
From your comments, maybe you can try something like :
ReferralStatus referralStatus;
try{
referralStatus = (ReferralStatus) int.Parse(status);
}
catch{
status = ((int)ReferralStatus.New).ToString();
referralStatus = ReferralStatus.New;
}
Related
I have a search input type in my form. When the form is submitted, the page reloads with query params with +
So if I search for abc def the query param becomes ?q=abc+def the url becomes https://localhost:44300/Search?q=abc+def
Now this is sent to the webapi as an api call. so then on server side I am replacing the + with space then performing the search on the controller. Now when I search for abc def+efg it becomes abc+def%2Bdef
request.Query = request.Query.Replace('+', ' ');
request.Query = HttpUtility.UrlDecode(request.Query);
So on server side I am first replacing the param's +s with a space character then decoding it and finally I get abc def+efg on the controller which is what I was looking for.
All this could be avoided if on the form submission the url was encoded. so if from beginning the query param was ?q=abc%20def%2Befg I would just need to decode it.
How to do that?
Edit
The page renders first, then a vue component gets the query parameter, and makes a call to api controller with axios. /api/search
const searchQuery = this.$router.getQueryParam('q');
this.queryParams.query = searchQuery ? searchQuery : null;
return axios.get(`/api/search`, {
params: queryParams,
});
If you were submitting a form, the urleconding would be automatically applied. Since you are getting and sending the search query without form submission, just apply a javascript function to encode that fetched value:
this.queryParams.query = searchQuery ? encodeURI(searchQuery): null;
You can do like this.
Uri.EscapeUriString(request.Query)
I'm building a form, where the number of questions, or inputs on the form varies depending on the value in a database.Each input on the form is a radio type. The name of the tags are dynamic and are loaded from the database using #db.row.questionID which would look something like: <span name=#id> and equal a value of 1 through whatever queries were requested.
My issue is, i wrote the form using post, and i want to submit the values back into a separate database, but i dont know how to request multiple values, that changes dynamically based on query.
Sample code i wrote, it doesnt give me any errors, but it doesnt give me any results either.
foreach(var prow in poll){
var Question = prow.PollId;
if (Request.Form["#prow.PollId"] == "A") {
int AnsA = row.ResultsA;
AnsA = AnsA + 1;
db.Execute("UPDATE Results SET ResultsA=#0 WHERE ResultsId=#1", AnsA, Question);
}
i have also tried:
if (Request["prow.PollId"] == "B") {
int AnsB = row.ResultsB;
AnsB += 1;
db.Execute("UPDATE Results SET ResultsB=#0 WHERE ResultsId=#1", AnsB, prow.PollId);
}
Do you want to get value in form with dynamic inputs? If yes, you can try this:
NameValueCollection nvc = Request.Form;
foreach (var item in Request.Form.AllKeys)
{
//do something you want.
// Examble : if(item == "A")// item will return name of input
// Note: nvc[item] return value of input
}
Update:
Request.Form.AllKeys will return all of input name in form.
We use foreach to lopp through colections of input name.
Use nvc[item] or Request.Form[item] to get value of input.
You can read this article :c#: get values posted from a form
I'll explain a quiet better here. I've this method wich returns me some lines of ma table according to a searchstring I informed in my textbox.
public ActionResult Index(string site, string searchString)
{
var user = from m in db.OrderDetails
select m;
if (!String.IsNullOrEmpty(searchString))
{
user = user.Where(s => s.Order.ClientID.Contains(searchString));
}
if (!String.IsNullOrEmpty(site))
{
user = user.Where(c => c.Order.SiteNumber.Contains(site));
}
return View(user);
}
In the same class, I've an other method which generate a pdf file (all the backend process is set up in a second project include in the first).
public ActionResult PrintOrders()
{
var user = from m in db.OrderDetails
select m;
return this.ViewPdf("Facture", "PrintView", user);
}
This second method, when it generate my pdf file, displays all the entries of my table. I would like that, when I click on my link (on the same page view wich display my table entries) for generate my pdf file, if I did a search before, I juste have fields that match my searchstring (or site string).
How can I implement it ? There is a way do to it ?
Thanks for your help, and sorry for the title which is maybe not too relevant. Also sorry for my english, hope you'll understand my aim.
EDIT INFORMATIONS
After looking, when I set up my PrintOrders() method like my Index() method as follow :
public ActionResult PrintOrders(string searchString, string username)
{
var user = from m in db.OrderDetails select m;
if (!String.IsNullOrEmpty(searchString))
{
user = user.Where(s => s.Order.ClientID.Contains(searchString));
}
if (!String.IsNullOrEmpty(site))
{
user = user.Where(c => c.Order.SiteNumber.Contains(site));
}
return this.ViewPdf("Facture Krys-Group", "PrintView", user);
}
and set my view like this :
#using (Html.BeginForm("PrintOrders", "Historic", FormMethod.Get))
{
Seach by ID : #Html.TextBox("searchString")
Search by Site : #Html.TextBox("site")
<input type="submit" value="Search" /></p>
}
then it works. But I've already the same form in my view for "Index" instead of "PrintOrders". How can I combine both ?
I am not sure I follow you completely but I think you achieve what you are looking for with the use of partial views. The form you mention can be a partial view that gets rendered into the pdf view and like that you really have one form but displayed in both pages. Hopefully I understood what you were after and this helps you.
I'm displaying a list of filtered items in a page, and now I have to limit the displaying by paginating the results.
So if I have url parameters like these:
example.com/?category=pizza&period=today
where both category and period can also not being showed:
example.com/?period=today
example.com/
how can I add a "Next page" in the end that keeps any previous parameter and adds
&pagenum=5
or if there are no parameters:
?pagenum=5
Tnx in advance!
For serverside
string url = Request.Url.GetLeftPart(UriPartial.Path);
url += (Request.QueryString.ToString() == "" ) ? "?pagenum=1" : "?" + Request.QueryString.ToString() + "&pagenum=1";
You can pass in the page number depending on how you are handling this.
For ASP.Net use the following:
string temp = Request.QueryString["yourParamName"];
Fissh
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.