Validation Summary For Ajax Call - asp.net-mvc

What is the best way to send back Validation Summaries back to the client when making an ajax call using jquery?

An easy way to achieve this is to have a div inside your page containing a partial with the validation summary. When you invoke the controller action using AJAX it would return this partial and you will be able to update the summary. Example:
$('#validationSummary').load('/home/someaction');
where the action would return a view:
public ActionResult SomeAction()
{
return View();
}
and the corresponding view:
<%= Html.ValidationSummary() %>
This way the controller action directly sends the partial HTML that needs to be updated/substituted inside your page. If your controller action returns JSON you will need to accommodate in your existing JSON structure an additional parameter containing the list of error messages so that in the AJAX success callback you could update the corresponding DOM sections. A bit more work here but with things like jQuery Templates this might even be fun :-)

You should return them back in Json. You can do this by return Json("Your Message")
If you're using ASP.NET MVC 3, look into the new remote attribute: http://davidhayden.com/blog/dave/archive/2011/01/04/ASPNETMVC3RemoteValidationTutorial.aspx

Related

MVC RenderAction return only renders partial part

I have this contact form which I want to use on two pages (two views) in MVC 5.x (razor viewengine) So I have put the form in an partialview called _Contact and I have read that RenderAction is the best approach if you do not have the required data for the partialview in your model and if it is more standalone (seperate from the rest of the view)
So I call it like this:
#{ Html.RenderAction("SendMail", "Uk");}
My Uk controller has these two methods:
[HttpGet]
public PartialViewResult SendMail()
{
return PartialView("_Contact");
}
[HttpPost]
public PartialViewResult SendMail(FormCollection fc)
{
// send mail using values out of the form (sorry did not feel like building a complete model for it
ViewBag.Succeed = true;
// if smtpclient could not reach server etc. it returns false
return PartialView("_Contact");
}
it all works, but the PartialView is only rendered, not on the placeholder where i call the RenderAction. It works all great, but after the post it just displays the partial view and not the "parent view" and the shared layout view etc. I hope that I made myself clear. Please let me know if I need to add more info.
This is the BeginForm from my shared view:
using (Html.BeginForm("SendMail", "Uk", FormMethod.Post))
It will not work as expected for your current code, because when you post the form, it returns Partial View not complete View. If you want to get only partial view then you have to submit your form via Ajax.
In ajax's success handler you will get HTML of your partial view and that you can put in a DIV tag of partial view container.
This link will give you a better idea about Posting Partial View via Ajax.
ASP.NET MVC Partial view ajax post?

ASP.NET MVC and strongly-typed partialview

I'm loading a partial view with an AJAX call:
public ActionResult LoadServerForm()
{
//data stuff
ViewData["ApplicationID"] = appID.ToString();
ViewData["Servers"] = ServersList(appServerRep.Session, null, appServers);
return PartialView("Application_AddServer");
}
This works great, but I'm trying to get away from magic ViewData strings. I tried making the partial view inherit from the same ViewModel as the "hosting" page, but the Model object is null when I try to this in the partial view:
<%= Html.HiddenFor(model=>model.Application_Key, Model.Application_Key) %>
Is there a way to pass the main page ViewModel down into the AJAX-loaded PartialView or should I be looking for a different approach altogether?
When you return PartialView("Application_AddServer");, you have to pass the model:
return PartialView("Application_AddServer", model);
Since this is an AJAX request, it's a separate controller action invocation, and the new PartialView doesn't know about the model of the requesting page. You'll have to reconstruct it, either from whatever your original data source is or from data passed with the AJAX request.

View Master Page and PostBack

I have a dropdown list on my master page that needs to postback after being changed. After the postback, whatever page initiated the postback needs to be re-displayed.
My question is where do I handle this? Obviously I do not want to have to modify every Action in my project... My guess is to maybe postback to some other fixed action and have that action redirect back to the page that is the referrer. Am I correct? Any thoughts?
Thanks.
Jason
In Site.Master, I ended up wrapping the dropdown within its own form that posted back to a dedicated controller/action.
<% Using Html.BeginForm("ChangeRole", "Home")%>
<div id="roleSelector">Change Role: <%=Html.DropDownList("Role", DirectCast(ViewData.Item("Roles"), SelectList), New With {.onchange = "this.form.submit();"})%></div>
<% End Using%>
In the controller I used the following code to change the mode and then redirected back to the referring URL.
<AcceptVerbs(HttpVerbs.Post)> _
Public Function ChangeRole() As ActionResult
Me.CurrentUser.SetRole(DirectCast([Enum].Parse(GetType(Models.ApplicationRoles), Me.Request.Item("Role")), Models.ApplicationRoles))
Return Redirect(Request.UrlReferrer.ToString())
End Function
I am unsure if this is the recommended way but I have been unable to think of another solution.
When you post back from the dropdown list change what are you doing? Can you maybe handle this in a jQuery call thus eliminating the need to re-display the page at all?
Calls to Action Methods can be asynchronous as griegs says, as such, you can post whatever information you need from the radio buttons to an action method without needing to reload the page.
If you need to update a part of the page, you can replace it with the contents of a rendered action method. If you use the jQuery ajax methods, you can post specific information to your methods.
For example, something like this:
$(document).ready(function()
{
$("#myRadioButton").change(function()
{
//Post to your action method, with the value of the radio button, function to call on success
$.post('yourActionMethodUrl', $(this).val(), function()
{
//Update some part of the page
});
});
});
This is based on memory, so you may need to check the syntax.

Asp.net mvc: Posting Back from the View

Is it considered better practice to post back to the same controller that did the rendering and redirecting from original controller if necessary? Or is it just the same if one jumps to different controllers from the view?
I create two overloaded actions in the controller, one to render the input form using an HTTP GET and the other to process the form post using an HTTP POST. Something like this:
public ViewResult Foo()
{
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ViewResult Foo( FormCollection form )
{
// process input
if (inputOK)
return RedirectToAction("Index");
return View();
}
The benefit of doing it this way is that if there's an error, the view gets re-rendered with any error and validation messages. If it's successful, there's a redirect to another action, which avoids the duplicate posting warning on browsers if a user refreshes the page - see Post/Redirect/Get on Wikipedia and this blog entry by Stephen Walther.
There are alternatives to taking a FormCollection, e.g. a list of simple parameters or binding to an object. See this article by ScottGu.
I think that the action that is being called should be contained within a relevant controller for that action. If the view needs to call the action it should call it from the relevant controller, not necessarily the controller that it was spawned from.
If you have an inventory controller you don't want to define actions that relate to administration even if an inventory screen might have an administration action on it, as an example.

How can I use Html.ValidationSummary with Ajax.BeginForm?

I have an AJAX form that I am creating in my MVC project. If the form is submitted using normal browser function and a page refresh occurs I get validation information rendered in the form (the built in MVC validation based on ViewData.ModelState).
Is there a similiar validation mechanism for AJAX forms?
<% using (Ajax.BeginForm("Create", "GraphAdministration", new AjaxOptions()
{
OnSuccess = "newGraphSuccess",
OnFailure = "newGraphFailure",
HttpMethod = "POST"
}))
{ %>
<!-- some form stuff in here !-->
<% } //end form %>
It really depends on where you are getting the content from to display once the form has been posted. The Validation summary is performed created on the server so that is where you have to do the work.
As an example I was using some partial content in an .ascx file to render a form. You get the form in the page the first time round by calling the action directly with Html.RenderAction
You would have your Ajax.BeginForm etc. in the .ascx file. Then call it directly in an action.
When the Ajax call is made from the browser you get it to post to the same action. That way you can do all of the server side validation that you would normally. You should set up the Ajax call to replace the original form with the new html that is returned by the action.
One thing that you have to be aware of is that the replace JavaScript will replace the content of an element not the element itself so remember to us the id of a surrounding element.
Apologies if that is a little convoluted, if you want more details just comment and I'll flesh out the relevant bits.
Extra Detail:
All of this assumes that you are doing all of the validation on the server.
You are going to have a View that has all of the page stuff in it and then some partial content in a .ascx file, this is where your ajax form lives, it needs to be set to replace content by id. Its easiest if it has the same name as the action your ajax is going to call.
You can use Html.RenderAction to get it into the View. You can also pass in data with other versions of the same method. Your essentially calling it in the same way your ajax code will.
You will need to wrap it all in a div with an id set. Use this id in the partial as the content to replace.
When you render the page the html for the form and all of the ajax stuff will get put in.
When the ajax action is called the partial content will be returned with any validation performed. It will replace the content of the div that you gave the id to.
You can have different versions of the action by using [AcceptVerbs(HttpVerbs.Get)] and [AcceptVerbs(HttpVerbs.Post)] attributes
The main problem with this method is that its not self contained, the div with the id is external to the partial.

Resources