How to prevent ajax form post with regular form post - c#

I have a Razor view that contains a normal form using Html.BeginForm. It also uses Html.RenderAction to insert a partial view that contains another form. I'm using RenderAction so the partial view can be strongly typed with it's own model. That partial view contains an ajax form using Ajax.BeginForm.
The problem I'm having occurs when the regular form in the parent view posts and has validation errors returned from the controller method. The ajax form validates as well and displays its own error messages. At first I thought it was just client-side validation picking up both forms, but when I set a breakpoint, I found that the controller method the ajax form posts to was getting called as well.
I would prefer to keep this view simple and not use ajax for both forms. For the same reason, I would rather not combine the forms into one and use javascript or other methods to differentiate between the two. What are my other options to keep the ajax form from posting or validating when the regular form posts?

My comment to #StephenMuecke finally triggered the right idea for the right keywords to google. And of course, the answer was already on StackOverflow. See Html.RenderAction uses Post instead of Get or How can I get Html.RenderAction to call the Get method on a Post?. #AndrewBarber's answer on the second link was a good answer. After I gave the GET and POST action methods for the ajax form different names and removed the [HttpGet] from the GET action method to allow it be called using either GET or POST, both forms work as expected.

Related

Possible to abort MVC action and keep view the same (without re-writing the view's GET "load code")?

Working on MVC5 web app.
I have a view based on a complex viewmodel. In the main GET method I'm filling this viewmodel, setting certain ViewBag items, etc.... I'll refer to this as the "load code" for now.
So, my view is basically a data entry form. Business rules are fairly complex. When the user hits the save button I do a POST and run some c# code which checks rules, etc... If it FAILS, I simply want to "abort" the action and show the user the same GET view.
My question involves all that was done to initially load the view: The ViewBag code, filling of viewmodel, etc.... Do I have to write this "load code" again in my POST? This seems very redundant. Is there a way I can just "abort" the ActionResult/POST and show the GET view?
I hope this makes sense. Thanks!
**** update/clarification - based on comments ****
I suppose this question is more of a "general" one. Can you "abort" the POST and go "back" to the GET View without re-running all the "load code" (for the dropdowns, populating the viewmodel, etc....)
If you want to go to server and validate and then decide if you want to accept the POST or Fails/Abort and keep the previous page with all the values
then I'll suggest you to handle this in AJAX.
Create a third action/API Method and keep your validation logic there. then on the form submit hit the validation action using ajax and server will return True/False (with any error message) if you get True from server then let the javascript post your form otherwise show any error message and return false to stop posting the form and stay on the page.
For example use a javascript method to validate.
<form onsubmit="return isValidForm()" />
function
function isValidForm(){
//// hit the server and see if you want to proceed with the POST
//// if fails return false so your form will not be posted and all of your values will remains the same, here before return false you can clear the form if needed.
}
let me know if you need more information.

Trouble loading a partial view from a different controller with model data

Quite new to MVC so please bear with me. I'm trying to load a partial view in a modal from a different controller and everytime I try to view it I get just an empty modal. I believe it is because I haven't been able to instantiate my model in the view.
E.g. I have a Controller 'Home' with a method 'Details' that returns a partialview from a different View folder. The native model to the controller is 'model', whereas the model belonging to my other controller is 'model2'.
public ActionResult Details() {
model2.User = user; //this is a global variable
model2.GetDetails();
return PartialView("~/Views/...Details", model2);
}
I'm sure the reason is because i'm missing the model data in the view. I tried adding another #model... to the view but clearly this doesn't work.
Is there a way of doing what I am trying to accomplish? It can even be a relatively dirty solution as this is a stopgap solution for the time being.
Reading back over this post it reads a little convoluted so if any clarification is needed please let me know.
Thanks
I faced this problem once before and i think it's a lot of work to reproduce it to provide an exact solution, but I can offer my 2 cents. The thing with browser Modals is that you need to provide a url when you are opening it. The URL will have to be the Controller/Action url and this is the tricky part which causes the problem. If you can figure that out, you should be able to solve the problem. If you can't, you can do one of the following:
1. Set the HTML content of Modal dialog from your main window's JS code after the Modal is opened.
2. Use one of the 3rd party HTML/CSS modal implementation, and set the HTML content from the JS code. In this case there is no browser modal and everything is on the same page.
To verify if the view is returning correctly from XHR, put the actionRoute URL in the browser address bar and you will see the content getting returned. It will help with troubleshooting.

Controller that calls a partial view that should display inside the Layout view

In a standard MVC application we have _Layout.cshtml and an Index.cshtml view. Now imagine if the user receives an email activation after a registration and now he/she clicks on that link.
The link points to /Account/ActivateAccount and after I process the activation, I wanted to redirect the user to the Login.cshtml partial view displaying a message.
I'm aware I can pass the message via the TempData["Message"] but what I don't know is how to redirect to a partial view and have that display inside the _Layout.cshtml instead that by itself.
At least this is what is happening when I call RedirectToAction("Login", "Home")
Note: all "home" based partial views are displaying within a < div id="divmain"> and my ideal solution would be to be able to decide what view should display inside that div, from the controller.
What's the right way to call a Partial View to be displayed from within another Controller ??
I'm not entirely sure I understand the question but I think what you're asking is if you can call a partial view from the _layout? This can be done with #Html.Action() helper. It will call out to a controller and method you specify and insert the result. The method you call would just be a PartialResult that returns the partial view with whatever data you need.
This is in contrast to #Html.Partial() which will render the partial view in place with whatever data you provide without routing back through a controller.
EDIT:
To summarize the comments to this answer, it seems I misunderstood the requirement. A user receives an email and clicks the link to activate their registration. The controller action that handles that request activates the user and then it needs to redirect to something. In this case, there was already a partial view which would serve the purpose but it couldn't be redirected to directly for some reasons. My suggestion was to just create a new View which contained a #Html.Partial() call to basically wrap the partial in a full view page.
The action method which handled the click could then just return that view directly or, if you consider the click of the link to be a "post" since it changes the application model by validating the user, you would create a new controller action and return RedirectToAction() directly. This would be like following the Post, Redirect, Get method and would prevent some issue if the user tried to refresh the "activated" page. It would also give more control over the URL naming.

Need clarification; Post from partial view with no JS

I've been searching for an answer to this question for a while now, I was hoping someone could give me clarity:
If I do a post from a partial View (or a called #Html.Action()) then there is no way save for usage of client-side scripting to have the application preserve state?
phrased differently: I can not post from a partial and just have it "do that part" and have the rest of the controllers remain as they were (provided no unsaved forms ofc)? Again with no java-script or the like.
What happens for me is that when I process the Http.Post and return a partial view, then that is the entirety of what gets written to the output pipeline and everything else in the browser vanishes.
I'm "solving" this right now by passing along a return-URL so I can redirect as an actionresult rather than send a partial view at the conclusion of the Http.Post processing. Is this the best I can do?
Use Ajax to update your partial view
this Question can be helpful for you
Update partial view after submit Ajax.Beginform

See which view contains the form that posted to a controller action

I have a contoller action that a number of forms will post to, all in different views.
Is there a way, in my controller action, to see which view contained the form that posted to it?
I need this to determine to where to redirect the action when the code in the post action is complete.
Thank you!
Two options...you can add a field to your form (or query string) that provides the redirect url. Or you can look at the HttpRequest.UrlReferrer field. It will provide you with the full URL which you have to parse to get the original form.
Hope this helps

Categories