How to make an async request and update url/querystring params? - c#

I am my first site with mvc 4, site uses heavy async requests and so far they are manageable, basically this is a page which display the records from DB in a grid and allow users to filter them based upon selection from some drop downs which make these requests.
Now the business requirement points to update URL when a filtration occurs so that users can share the filtered records via copy pasting URL, I am wondering if there is a way to achieve it like how instagram show's an image on click in a model popup and also updates the URL so user can share it and so does twitter when navigated through home to notifications.
Any suggestions would be highly appreciated.
Thanks in advance.

Instagram uses the Javascript History API to change the URL via javascript, without a redirect. Take a look https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
// Suppose http://mozilla.org/foo.html executes the following JavaScript:
var stateObj = { foo: "bar" }; history.pushState(stateObj, "page 2",
"bar.html"); This will cause the URL bar to display
// http://mozilla.org/bar.html, but won't cause the browser to load bar.html
// or even check that bar.html exists.
For an MVC-friendly js library, you can use History.JS http://balupton.github.io/history.js/demo/?state=2

Related

How can I add items in the view, but sequentially

I have a page with for example personal data, I want to have a Go button for other items such as job data but on the same current page with a Go button (next) and so on...
What is this characteristic called Please provide a link to it, or a brief explanation. (like multiview in old version 'asp.net web form')
I'm using asp.net core
This problem could be solve by using ajax.
In your controller you have to make a action just like this
public JsonResult GetYourData()
{
//Add your data here. Make a string along with your data like '<h2>Job Data</h2><p>Title:Software-Developer</p>'
return Json(yourCreatedString, JsonRequestBehavior.AllowGet);
}
Now in view you could add an event on the button click, ask for this above action, get the html in string format, and append that to your DOM

Dynamic data for JQuery in ASP.NET pages

Problem
I have some pages that need dynamic data from website to generate output to users.
A simple solution is an aspx(php, ...) page to generate data and create another html page serving as GUI retrieving data from first page and showing it to users. in this method I can call my GUI page for example form1.aspx and my data page form1.json.aspx.
although I personally like this method, it is not suitable when creating components for it.
Another method that currently I'm using is using same GUI page call itself with a querystring to retrieve data. this page should check for that query string and if it exists, only generate data and remove everything else from page. As an example for this method if I call my page form1.aspx, to retrieve data, I need to call it like form1.aspx?JSON
Here is an example of what I'm doing:
protected void Page_Load(object sender, EventArgs e) {
if (Request.QueryString.ToString().IndexOf("JSON") == 0){
this.Controls.Clear();
Response.Clear();
// send pure data to client
} else {
// render page as GUI
}
}
However this method becomes too messy if I add master page and/or inherit my page from some template page. Master pages can only removed in Page_PreInit and that adds another extra method.
Security controls cause another problem, if user leaves page open for long time until session expires any attempt to retrieve data will fail cause security module will redirect the request to login page.
Next problem is I cannot consolidate my component in package because it needs modification in page (removing master page, clearing page components ...).
What I'm looking for:
1- I'm looking for a solution that I can call my page and get pure data (JSON or XML format) and doing so run a server side method that generates data, so I don't have to worry about what another designer puts in their master page or template.
2- I think it is possible to use axd extension to do this but I don't have a clue about it and couldn't find a helping document either.
3- Is there any better way of doing this. any suggestion or solution to improve this much appreciated.
Page methods. Check this article: http://weblogs.asp.net/craigshoemaker/archive/2008/09/29/using-jquery-to-call-asp-net-ajax-page-methods.aspx or http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
WCF JSON service: http://www.codeproject.com/Articles/327420/WCF-REST-Service-with-JSON
Other ways of doing is using an HTTP Handler. Implement IHttpHandler interface and register your implementation in your Web.config file. Later call it using jQuery ($.get / $.post):
http://msdn.microsoft.com/en-us/library/46c5ddfy.aspx
EDIT
As OP pointed out, in order to access session state in a page method you should use WebMethodAttribute this way:
[WebMethod(EnableSession = true)]
I think you can use webservice instead of aspx page to return a JSON or XML string and then the caller page (any aspx page) will response after process is success.
So with this webservice, any third party page will have access to your server side method.
To create a webservice pls Check this link: Create and use Asp.net web service basic
Regards

Filling a HTML form with C#

I need help with connecting to a certain website via my username & password.
With WebClient I can fill the username field and the password field, but how do I invoke the click method of the button?
And How can I fill a specific textBox that doesn't have an ID?
I tried doing this with webBrowser, but every time I navigate I have to use a new function every time, which makes the work much harder.
Thanks.
What you're trying to do is wrong. If you want to Post some data to a web address (a URL), simply create a web form (a simple HTML form), fill it, and then send it. Just consider these notes:
Your HTML's form action should be the exact URL of the form you're imitating.
Your input controls should have the same name attribute value.
For more information, see Form Spoofing
Look at the web browser control and see if you can use that inside your windows form to perform the task that you are doing. Once you are satisfied with the results, you can make the web browser control invisible, and it'll work just like you do with web response and request calls.
View the source code and find the id of the button (say "Login").
Then use:
HtmlElement elem = webBrowser1.Document.GetElementById("Login");
if (elem != null)
elem.InvokeMember("click");

Best practice for attempting to edit an item that doesn't exist?

I currently have this controller function:
public ViewResult Edit(int id)
{
//get user from id
var user = _adminRepository.GetUser(id);
return View(user);
}
This currently gives me an error on my view page if I attempt to edit an item with an id of 100, when there is no user with an id of 100 in the database.
What's the best practice for handling this? Send them to a Create page, or show a friendly error message? Should that redirect functionality be within the controller function?
IMO it should raise a 404 error. After all the user is requesting a resource that does not exist, much like a regular web page.
I would display a friendly error message telling them that the user had been removed and provide a link to the Create User page if they want to recreate the user.
I'm against redirecting the user anywhere they didn't originally intend to go, so automatically redirecting them to the Create User screen when they expected to go to the Edit User screen (I'm assuming they're separate) is not the most user friendly solution.
I think you should redirect them to Create Page with an Extra information as to why they are redirected.
Based on your reply to #RPM1984, i think your problem is with the Update Action since you already have the view opened. i suggest you do redirect to friendly error page saying "The user you are trying to update doesn't exist." when you click save then find out the user isn't there anymore. With a link to go back to your grid and see the latest set of users.
This page would be helpful also for some users might try to access the url directly instead of using your grid..
i.e.
some may type
http://mysite.com/users/edit/215215132
where 215215132 is your userId.
i'm just assuming this is how you do it.

ASP.NET Postback and URLs

I have a page that requires the user to go through several steps, however step is performed on the same ASPX page with different panels being displayed.
However this is a requirement that each step has a different URL, this could be a simple as a query string parameter, for example:
Step 1:
/member/signup.aspx?step=1
Step 2:
/member/signup.aspx?step=2
Step 3:
/member/signup.aspx?step=3
However I don't want to have to redirect the user to the new URL each time they continue to the next step, this would involve a lot of redirecting and also a switch statement on the page load to work out which step the user is on.
It would be better if I could alter the URL that is displayed to the user when the original request is sent back to the user, i.e. the user click "next" on step 1 the page then does some processing and then alters response so that the user then sees the step 2 URL but without any redirection.
Any ideas would be greatly appreciated.
Could you convert your Panels into steps in a Wizard control?
It would be a little more complicated than you probably want, but you could achieve this effect with the PostBackUrl property of the submitting button. I'm assuming each panel has its own "submit" button, and they could all use this property to "advance" the process. The drawback is that in order to get to submitted controls, you'd need to use the Page.PreviousPage property in order to access any controls and their values.
You could programmatically alter the PostbackUrl property of your 'Next' button on each Page_Load, based on the query string value. This is a bit strange though, as you wouldn't be able to use a standard event handler for the button click, and you'd have to use the PreviousPage property of the Page to get the data from the previous tab.
I'd say challenge this requirement. Why would anyone need to jump into the middle step? If it's a case of displaying the progress to the user, do this on the page, not in the URL.
You require that each step has different URL, than Response.Redirect is the only option. As you want to avoid the redirection, you can use IFrame but IFrame URL is not visible to user on his browser. I think redirect option is ugly(for both SERVER and CLIENT) as in this case, you first post on the page and than get that page. The best solution is POST BACK with some varible tracking step.
You could implement a form or url rewriting so that your urls end up being
/member/signup/step1/
/member/signup/step2/
/member/signup/step3/
To do this use the
HttpContext.RewritePath method which means you can rewrite /member/signup/step1/ to /member/signup.aspx?step=1 for example. See an example here.
I would also use the PRG (post request get) pattern so that each next link posts the form data of that step to the session then redirects the user top the correct next url. this will ensure that the user can navigate back and forth through the steps safely and also the url will remain intact in all your posts.
Check out server.transfer

Categories