asp.net mvc expected controller and action not getting invoked - asp.net

I have a weird issue. I loaded a page using "LoadMyPageController" and there is an ajax_submit_button1 which can be used submit the page.
Also there is another ajax_submit_button2 to print the page. This button submits the view model of the page as a whole to the "PrintController" which has a "PrintData" action.
Now when I hit the "ajax_submit_button2", my PrintController.PrintData is not invoked. Instead when I check my fiddler tool the request is made as
http://localhost:18484/LoadMyPage/PrintData?Length=14
which is an invalid URL.
I have contructed my ajax_submit_button2 in such a way that it should invoke
http://localhost:18484/Print/PrintData?Length=14
But I don't know why LoadMyPage controller is present in my URL.
Any thoughts or comments would be appreciated. By any chance does asp .net MVC decides that it will take a default controller on its own if it can't find the controller action for any reason.
The code is a kind of tightly coupled so can't post it. I want to know if anyone experienced a problem like this.

This has nothing to do with the routing on the server since the request being made by the client has the wrong controller in it. I suspect that your code generating the url for the submit button is not correct -- i.e., not specifying the controller to be used -- or that you have a form around the submit button that is actually being invoked instead of (or in addition to) the ajax code. Note that if your submit handler doesn't return false, the default form action will be invoked and the form submitted normally. If you do have a form, make sure that the url on it is correct and that your submit handler returns false.
$('#printForm').submit( function() {
$.ajax({
url: $(this).attr('action'),
...
});
return false; // this is important!
});

Related

Detecting redirect to a different URL

I am using ASP.NET MVC with AngularJs framework. In my home controller I'm checking if there is a valid license and if not, I'm re-directing to a page to import license with this code:
public ActionResult Index()
{
var retVal = _licenseProvider.ValidateExistingLicense();
if (!retVal.Item1)
{
Response.Redirect("DataMaintenance/ImportLicenses", true);
return View("DataMaintenance/ImportLicenses");
}
So, in my ImportLicenses controller I want to detect that I was re-directed vs. called from the menu. I found an older thread about redirecting to a different action, but that solution doesn't apply. What are my options here?
You have a couple of options here:
Add a query string parameter in the ImportLicenses action that
determines whether the user got here via a redirect or the menu
Set a TempData variable before redirecting your user to the
ImportLicenses action.
Use a Session variable
Read this for more information about passing data between Action methods.
It really depends on your constraints, there are a number of options. Without knowing much about your project. My first suggestion would be to drop a cookie before redirecting, then when the request comes in to the ImportLicenses action you can check for the check, and delete it, but include whether or not the cookie was found in your view model so you can reflect this in the UI.
There are other options like using session state, or a query string parameter. A querystring parameter could be just as effective as the cookie idea i mentioned above, and it would be a bit cleaner.
If you can provide more information about your use case, I may be able to expand my answer.
Hope this helps.
In the meanwhile I decided to do a little bit of cheating, but it worked. In the menu I changed the original call to this
dataMaintNodes.SubNodes.Add(new MenuMapNode() { LabelKey = "importLicense", Action = "ImportLicenses", Controller = "ImportLicenses", Area = "DataMaintenance", Icon = "", Roles = "IMPORTLIC" });
In other words, instead of normal Index action I introduced a different action. I added that new action to my controller and just set the ViewBag property to false when called from the menu and to true in the Index action that is called by Redirect. So, it's a cheating, but it works. I only wanted to display Cancel button on that modal dialog when I am calling from the regular menu and no Cancel button when called from the home controller. Now, my second problem is that Modal Dialog doesn't really prevent from escaping from it and continuing working with the application. So, we may want to introduce more logic.

Submit form to both code behind and third party url?

I have a legacy app that I need to change to accommodate a new payment processor.
The app is Asp.Net.
Without reconstructing the app (not in the budget) I need to take the final form and save information from it in the code behind, like it currently does, then I need to submit that same form to a third party url. Ideally as one button push to the end user.
I'm drawing a complete blank on a way to do this. Any suggestions?
Forgot to mention that JQuery and javascript are both valid tools for a solution.
You could create a javascript function that's bound to the form submit button's click event, or the form's submit event. The function will need to prevent the default form submission from firing. Use jQuery to serialize the form data, and create a synchronous AJAX request to submit the data to the third party. After the ajax submission has completed, you can trigger the form submission to the code-behind. If the ajax fails to submit properly, you can optionally abort the form submission to the code-behind.
You may need to account for XSS security, so look into cross-origin resource sharing and the Access-Control-Allow-Origin header.
Another option would be to have the code-behind behave as an http client and submit the form data to the third party.
so currently it's saving the results via code? Well, you could hack it by putting some javascript on the page that read's the forms values and posts them (eg with jquery), before doing you actual asp post.
edit (something like this might help (in some cases):
//change the action of the form (you could just change in code or this
$('#myform').attr('action','http://newpaymentproc.com/me/');
//override the default submit
$('#myformsubmitbutton').click(function(){
//extract the form data somehow (depends on form)
var formObj;
$.each($('#myform').find('input').serializeArray(), function(i, field) {
formObj[field.name] = field.value;
});
//post to old place
$.post('/old_current.asp', formObj).then(
//after posting to old place and getting response...
//submit form to new payment processor
$('#myform').submit()
);
// Cancel the actual form submit click to give time for post
return false;
});
Another way would be to have the legacy code (after submission) spit out a form with the data in it and some javascript to trigger submit on page load.
After the original process has completed, just take the submitted form data and push it to whichever URL you're working with. It requires minimal modification on the original app.
I have no code to go on, so I have no code to give. Hope that helps!

Clear server validation message before submit

To replicate the issue:
Create an ASP.NET MVC 3 page with server validation.
Submit with validation error.
Server validation error appears in red.
Correct the validation error and submit again, then Success
redirected to another report page.
On clicking the Back button on the report page, the validation error
message still showing on the original form.
Users getting annoyed seeing the server validation message when clicking the back button.
I would not consider a solution to disable the back button.
I would not consider a solution to refresh the page on clicking the
back button.
I would consider the server validation message to disappear before making the successful form submission or any other valid solution.
Thanks
Here are some methods for clearing history so that back button will not show remembered page: http://www.codeproject.com/Tips/135121/Browser-back-button-issue-after-logout
To avoid seeing the validation message, I disable the cache so browser will automatically reload the page when users click Back button. However, users would see a form resubmission warning if the page was previously submitted using POST method. To workaround this, I use javascript window.history.back() to change a POST request back to the prior GET request if the ModelState is not valid.
Here are the details...
Create two functions in controller: one with [HttpGet] attribute and one with [HttpPost] attribute.
In the HttpPost version, add following logics...
If ModelState is invalid, save ModelState and form/model data to TempData
Return a simple View that contains javascript like following.
<html>
<body>
<script>window.history.back();
</script>
</body>
</html>
In the HttpGet version,
Add attribute [OutputCache(NoStore = true, Duration = 0)]
Add logic to load ModelState and model data from TempData
Pass model data to View

ASP.net 4.0 Webforms Routing Postback Issue

We are using asp.net 4.0 and routing with web forms to create friendly urls.
The routing is working fine except that the correct "action" value is not being assigned to the form element in the master page for any route that has multiple levels.
For example, the route ( customer/{customerid} ) when browsed to with .../customer/12345 only displays 12345 in the "action" attribute of the form. The issue with this is that it isn't complete and any postback fails and gives an error "The HTTP verb POST used to access path is not allowed" If I updates the action as "customer/12345" (using Firebug), the postback works fine.
It even errors when using static routes like customer/customer, it only puts "customer" and not "customer/customer" as the action value of the form. Basically, only putting the last piece of the route into the action attribute instead of the whole route. Why?
Any ideas on how to correct this?
You can work around this by overiding the form action as form1.Action = Request.Url.PathAndQuery;]in the Page_Load event
See this related Topic.
It uses Request.RawUrl instead of Request.Url.PathAndQuery, which seams to return the same value.

How do I use the "Post/Redirect/Get" a.k.a. "Redirect after Post" with asp.net

Doing a refresh after certain action in asp.net seems to make them happen again even when that action doesn't make sense (think double delete). The web way to deal with this situation is to redirect after a post to get a clean version of the page that can be refreshed without reposting an action to the webserver. How can I do this with ASP.NET
I have a feeling there is a deeper problem I'm not getting but here goes. In your postback event:
// the post handling logic, e.g. the click event code
Response.Redirect(Request.RawUrl);
Use Server.Transfer method.
The Server.Transfer method has a second parameter—"preserveForm". If you set this to True, using a statement such as Server.Transfer("WebForm2.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to.
http://www.developer.com/net/asp/article.php/3299641

Resources