Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I finally found the solution to the problem. I implemented it with AJAX and ended up with the following code:</p> <p>_Index.cshtml</p> <pre><code>&lt;header&gt; &lt;h2&gt;Subscribe&lt;/h2&gt; &lt;/header&gt; &lt;p&gt;Subscribe to my e-mail newsfeed.&lt;/p&gt; &lt;div id="subscription-form"&gt; @{Html.RenderPartial("_Form");} &lt;/div&gt; </code></pre> <p>_Form.cshtml</p> <pre><code>@using Blog.Models.Entities @model Subscriber @{ AjaxOptions ajaxOptions = new AjaxOptions { LoadingElementId = "loading", LoadingElementDuration = 2000, HttpMethod = "Post", UpdateTargetId = "subscription-form" }; } &lt;div id="loading" style="display: none;"&gt; &lt;p&gt;Processing request...&lt;/p&gt; &lt;/div&gt; @using (Ajax.BeginForm("Index", "Subscription", ajaxOptions)) { &lt;div class="editor-label"&gt;@Html.LabelFor(subscriber =&gt; subscriber.Email)&lt;/div&gt; &lt;div class="editor-field "&gt;@Html.EditorFor(subscriber =&gt; subscriber.Email)&lt;/div&gt; @Html.ValidationMessageFor(subscriber =&gt; subscriber.Email) &lt;input type="submit" value="Subscribe" /&gt; } </code></pre> <p>_Succes.cshtml</p> <pre><code>@using Blog.Models.Entities @model Subscriber &lt;p id="subscription-result"&gt;@ViewBag.Result&lt;/p&gt; </code></pre> <p>And the following controller action methods:</p> <pre><code>public ActionResult Index() { return PartialView("_Index"); } [HttpPost] public PartialViewResult Index(Subscriber subscriber) { if (ModelState.IsValid) { Subscriber foundSubscriber = _repository.Subscribers.Where(s =&gt; 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("_Succes", subscriber); } ModelState.AddModelError("Email", "Please provide a valid e-mail address."); return PartialView("_Form", subscriber); } </code></pre> <p>I hope this will help anyone trying to achieve the same in the future. BTW, I found the solution on this blog: <a href="http://xhalent.wordpress.com/2011/02/05/using-unobtrusive-ajax-forms-in-asp-net-mvc3/" rel="nofollow">http://xhalent.wordpress.com/2011/02/05/using-unobtrusive-ajax-forms-in-asp-net-mvc3/</a>.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload