I have a blog that has a sidebar with a partial view in it that enables users to sign up for my e-mail newsfeed. What I’m trying to do is returning the user to the page they came from after posting some data, and displaying any validation or return messages in the form’s partial view.
The problem is that my partial view opens in a new window (without the lay-out). How can I fix this so it returns to my blog, with the return data in de sidebar?
This is my view:
@using Blog.Models.Entities
@model Subscriber
<header>
<h2>Subscribe</h2>
</header>
<p>Subscribe to my e-mail newsfeed.</p>
@using (Html.BeginForm("Form", "Subscription"))
{
<div class="editor-label">@Html.LabelFor(subscriber => subscriber.Email)</div>
<div class="editor-field ">@Html.EditorFor(subscriber => subscriber.Email)</div>
@Html.ValidationMessageFor(subscriber => subscriber.Email)
<input type="submit" value="Subscribe" />
<p>@ViewBag.Result</p>
}
And the relevant pieces of controller that are processing the data:
public ActionResult Form()
{
return PartialView("_Form");
}
[HttpPost]
public ActionResult Form(Subscriber subscriber)
{
if (ModelState.IsValid)
{
Subscriber foundSubscriber = _repository.Subscribers.Where(s => s.Email.Equals(subscriber.Email)).FirstOrDefault();
if (foundSubscriber != null)
{
ModelState.AddModelError("Email", "This e-mail address has already been added.");
return PartialView("_Form", subscriber);
}
_repository.SaveSubscriber(subscriber);
ViewBag.Result = "Succesfully subscribed to the newsletter.";
return PartialView("_Form");
}
ModelState.AddModelError("Email", "Please provide a valid e-mail address.");
return PartialView("_Form", subscriber);
}
I finally found the solution to the problem. I implemented it with AJAX and ended up with the following code:
_Index.cshtml
_Form.cshtml
_Succes.cshtml
And the following controller action methods:
I hope this will help anyone trying to achieve the same in the future. BTW, I found the solution on this blog: http://xhalent.wordpress.com/2011/02/05/using-unobtrusive-ajax-forms-in-asp-net-mvc3/.