How to prevent redirection on form submission in ASP.Net MVC 3, and just stay on the page? - asp.net-mvc-3

I have two forms in one View. One of them does the job of uploading pictures to the database.
I need the whole page -and the data the user has typed into the "other form"- to remain untouched, meanwhile the user could also upload pictures. But it doesn't work.
The problem is that when the user submits the photos, the whole page changes. And worse than that, the new page only contains the "photo uploading" form !! Because upon Return View(); of the "upload pictures" Action method, it's View is rendered. :/
Look at the action method:
public ActionResult Upload(IEnumerable<HttpPostedFileBase> files)
{
//Upload the pictures .
return View();
}
Is it possible to achieve the result I need only by changing the return type of the Action method, (maybe ?) in order not to render anything and say just show a message to the user like "Files have been uploaded!" ??
Or should I use Ajax instead ?
Thanks for the advice, in advance ;)

You can't upload files using AJAX but you could use some third-party components that will upload files using hidden iframe which mimics like AJAX. You can google jquery ajax upload plugin.
For the other form you can use Ajax.BeginForm/PartialView to avoid complete refresh.

If the views are strongly typed against a model then you can always pass the model back to the user to "refill" the constant form (probably worst option). Another option (probably best) would be ajax of course.

Related

RedirectToAction MVC 3 after $.ajax call

From my view I am sending via $.ajax a JSON object to my controller to save it in the database.
If all succeeded i want to redirect to another action which will show a diferent view.
If i use this code:
return RedirectToAction("CreatePage", "Survey", new {id = question.PageId});
The execution goes to the Survey controller which returns a view but it is not shown.
I have read some post which said that it is not posible to redirect via ajax.
The solution I use so far is to redirect via javascript like this:
success: function (ret) {
window.location.href = "/Survey/CreatePage/" + $("#PageId").val();
}
Although this always works, sometimes i need to refresh the CreatePage view to show the last changes made.
Any idea of how to solve this problem better?
Thanks in advance
As mccow002 suggested, I wasn't really needing to make the call via AJAX for that part. After studying the solutions suggested, i realized that i could simple submit it in a form. My confusion came because I have a save and continue editing and a save. For the save and continue I use the AJAX call, but for the save option with the form being submitted is ok.
Thanks very much for your help.
Instead of redirecting to a new page, you can send a rendered html from .net code back to client and load that html in page, like this $("#main").load(renderedHtml).
But for refreshing the page you can write a simple script that run at specified intervals and refresh the page contens.
You could use [OutputCache] on the CreatePage action so that it doesn't cache the page or only caches for so long.
output caching

Codeigniter AJAX and POST

What is the best way to address an AJAX script that sends data to POST in codeigniter? Right now I am loading a view with the AJAX through $this->load->view('AJAX', $data); however there is no UI or user actions in the view. It's simply running through the script and returning POST data a little after the script loads. I receive the POST data in my model where I input the values into the DB and output some other values based on the data.
I need to open a real view, set metatags and re-direct the user to another website afterwards.
How do I address this?
The problem I'm facing is that I cannot open up another view because the AJAX view is the one that's in focus but I need this AJAX view to be temporary that basically does it's thing and sends to POST.
Is there any convention that I can lookup/research to what I'm describing? Let me know what kind of clarification is needed if any.
Some people like to write "ajax" controllers and post to them exclusively, but you don't need to do that. You can handle the request in the same controller that handles the non-ajax request. Personally, I exclusively return json, but you can return chunks of HTML if that works better for you.
Your exact problem is vague (actual code would help clarify), but I think you are on the wrong track. Don't use a view for processing anything ever. Use your Controller layer, this is for handling input and requests.
Example of controller method responding to either ajax or non-ajax request:
function edit_user()
{
$data['status'] = $this->user_model->save();
if ($this->input->is_ajax_request())
{
// return json string with our update status
// Something like: {"status":true}
echo json_encode($data);
exit;
}
// Load the non ajax view with the same data
$this->load->view('users/edit', $data)
}
$this->input->is_ajax_request() is a function of the Input class that reads $_SERVER['HTTP_X_REQUESTED_WITH'] and checks if it's value is XMLHttpRequest. This should only be true if it's an "ajax" request.
You can make life easier by wrapping this in a class or function. No matter what you decide to do, don't use the view layer for processing data.
I think my problem is, how do I address javascript without a view? how do I call the script and/or where do I put the JS code in the controller? I felt it was the wrong direction to address the code in a view but I didn't see how else to do it.
Whenever possible, you should put javascript code in a .js file and use a <script> tag to load it, in an HTML document. The only other exception is putting it in a "view" file (a file that's only purpose is to construct your final HTML output). In other words, follow the same rules of HTML as to where to put javascript, and follow the usual conventions of MVC of where HTML belongs (in the view). Javascript code does not belong in your controller. Javascript is not processing your data, it is sending the data to the server.
I need to open a real view, set metatags and re-direct the user to another website afterwards.
If you want to load a view, then redirect (after a certain amount of time I assume), you can do it with javascript or a <meta> tag (but don't use a meta tag, use js).

ASP.NET MVC Redirect to action without a physical redirect

Are it in any way possible to execute another action in the same on in another controller from an action, action filter or in any other way without doing a physical redirect.
The reason for this is that I have a dynamic paging system, where the user will load a url, for an example
/1/some-page-title
This url is maped to the controller “Home” and the action “Element”, this action will then load a row from the database where the element id is “1”. Depending from the data on the element from the database will the page be rendered as a contact form, an image gallery and so on.
Now I could map the paths so
/Page/1/some-title/ will render a normal html page,
/Contact/1/some-title/ will render a contact form
/Gallery/1/some-title/ will render a gallery
But I would prefer the paths to be simple.
There are problems with this answer, it's been a long time since I did anything thing with ASP MVC, so I'm not actually aware of what the problems are.
Unfortunately I can't delete an accepted answer.
So, I'm striking through the answer as it was, if you can actually answer this, or make it better, please do so.
Yes, very simple really :)
Say you're in controller C action A. You want to "redirect" to controller B action Z, just call the other controller action from the current one, returning it's result.
public ActionResult A()
{
return B.Z()
}
You may be looking for Html.RenderAction or Html.Action. However, these are used in the view and not the controller.

CodeIgniter jQueryUI dialog form example

I am trying to use CodeIgniter and jQuery-ui dialog to create a modal window with form to update user information.
The process should be like:
1. Press a button on a view page.
2. A modal window pops up.
3. Inside the window is a form that a user can fill.
4. If the user filled something before, the information should be shown in corresponding field
5. Click the update button on the modal window to save the changes to database.
Can anyone provide a good sample of this process?
I used ajax to pass the data but it didn't work when I was trying to update the data to the database. It would be nice if an example of how to pass data from ajax to php and how php handle that.
Thanks,
Milo
well the jquery bit for post(), get(), ajax() works the same in any measure you would normally use it.. key difference here is with CI you can't post directly to a file-name file-location due to how it handles the URI requests. That said your post URL would be the similar to how you would access a view file normally otherwise
ie: /viewName/functionName (how you've done it with controllers to view all along. post, get, ajax doesnt have to end in a extension. I wish I had a better example then this but I can't seem to find one at the moment..
url = '/home/specialFunction';
jQuery.get(url, function(data) {
jQuery("#div2display").html(data);
});
in the case of the above you notice despite it not being a great example that. you have the url with 2 parameters home and specialFunction
home in this case is the controller file for home in the control folder for the home file in views the specialFunction is a "public function" within the class that makes the home controller file. similar to that of index() but a separate function all together. Best way I have found to handle it is through .post() and a callback output expected in JSON cause you can form an array of data on the php side json_encode it and echo out that json_encode and then work with that like you would any JSON output. or if your just expecting a sinlge output and not multiples echoing it out is fine but enough of the end run output thats for you to decide with what your comfortable doing currently. Hopefully all around though this gives you some clairity and hopefully it works out for you.

Hot to implement grails server-side-triggered dialog, or how to break out of update region after AJAX call

In grails, I use the mechanism below in order to implement what I'd call a conditional server-side-triggered dialog: When a form is submitted, data must first be processed by a controller. Based on the outcome, there must either be a) a modal Yes/No confirmation in front of the "old" screen or b) a redirect to a new controller/view replacing the "old" screen (no confirmation required).
So here's my current approach:
In the originating view, I have a <g:formRemote name="requestForm" url="[controller:'test', action:'testRequest']", update:"dummyRegion"> and a
<span id="dummyRegion"> which is hidden by CSS
When submitting the form, the test controller checks if a confirmation is necessary and if so, renders a template with a yui-based dialog including Yes No buttons in front of the old screen (which works fine because the dialog "comes from" the dummyRegion, not overwriting the page). When Yes is pressed, the right other controller & action is called and the old screen is replaced, if No is pressed, the dialog is cancelled and the "old" screen is shown again without the dialog. Works well until here.
When submitting the form and test controller sees that NO confirmation is necessary, I would usually directly redirect to the right other controller & action. But the problem is that the corresponding view of that controller does not appear because it is rendered in the invisble dummyRegion as well. So I currently use a GSP template including a javascript redirect which I render instead. However a javascript redirect is often not allowed by the browser and I think it's not a clean solution.
So (finally ;-) my question is: How do I get a controller redirect to cause the corresponding view to "break out" of my AJAX dummyRegion, replacing the whole screen again?
Or: Do you have a better approach for what I have in mind? But please note that I cannot check on the client side whether the confirmation is necessary, there needs to be a server call! Also I'd like to avoid that the whole page has to be refreshed just for the confirmation dialog to pop up (which would also be possible without AJAX).
Thanks for any hints!
I know, it's not an "integrated" solution, but have you considered to do this "manually" with some JS library of your choice (my personal choice would be jQuery, but any other of the established libraries should do the trick)? This way you wouldn't depend on any update "region", but could do whatever you want (such as updating any DOM element) in the response handler of the AJAX request.
Just a thought. My personal experience is that the "built-in" AJAX/JS stuff in Grails often lacks some flexibility and I've always been better off just doing everything in plain jQuery.
This sounds like a good use-case for using web flows. If you want to show Form A, do some kind of check, and then either move onto NextScreen or show a Dialog that later redirects to NextScreen, then you could accomplish this with a flow:
def shoppingCartFlow = {
showFormA {
on("submit") {
if(needToShowDialog())return
}.to "showNextScreen"
on("return").to "showDialog"
}
showDialog {
on("submit").to "showNextScreen"
}
showNextScreen {
redirect(controller:"nextController", action:"nextAction")
}
}
Then you create a showDialog.gsp that pops up the dialog.
--EDIT--
But, you want an Ajax response to the first form submit, which WebFlow does not support. This tutorial, though, will teach you how to Ajaxify your web flow.

Resources