Ajax call to update div on failure, or redirect to page on success
Background:
I have a popup which lets me create a company, this popup has a text field called company name, and this is a required field (using the [Required]
data annotation on the backing view model).
<div class="popup-editor">
<h4 class="popup-title">
Add new Company</h4>
@using (Ajax.BeginForm("Create", "Company", new AjaxOptions { UpdateTargetId = "popup-editor", OnSuccess = "$.validator.unobtrusive.parse('form');" },))
{
@Html.ValidationSummary(true);
<table>
<tr>
<td class="label">
Company Name
</td>
<td class="editor-field">
@Html.EditorFor(x => x.Name)
@Html.ValidationMessageFor(x => x.Name)
</td>
</tr>
</table>
<div class="popup-buttons">
<a href="#" onclick="return togglePopupEditor();"开发者_StackOverflow社区>Cancel</a>
<input type="submit" value="Add Company" />
</div>
}
</div>
Now the validation works correctly and the ajax lets me show an error message in the popup when the name field is empty.
Problem:
When there are no validation errors I need to be able to redirect to a new page (company details page), but instead this page is inserted into the div where the popup contents were. For example:
public ActionResult Create(CreateCompanyModel model)
{
if(!ModelState.IsValid)
{
return PartialView("_AddCompanyEditor");
}
Company c = CompanyService.Create(model.Name);
return RedirectToAction("Details", new { companyId = c.Id });
}
Is there any way to either; force a complete redirect for the entire page, or switch to a standard HTML form?
Not really. Browsers handle AJAX redirects without notifying the calling javascript of what happened. One option would be to return a small snippet of HTML that contains a javascript tag that redirects the page. The jQuery handling on the client side should pick that up and run it.
Most other options would involve changing your AjaxOptions to run a method that watches for something specific in the results and acts in a different way depending on the response. For the project I work on currently, we have all of our AJAX requests go through a special "event framework," so that different actions can be performed depending on which events get returned from the controller action.
精彩评论