Search code examples
asp.net-mvcasp.net-mvc-4razor

Posting form located in partial view


I am new to MVC 4 and razor, I have layout view contain form located in partial view,

My model:

public class SubscribeModel
{
    [Required(ErrorMessage = "Veuillez saisir votre adresse mail pour s'inscrire ...")]
    [EmailAddress(ErrorMessage = "Vous devez saisir une adresse mail valide \"Ex: [email protected]\"")]
    public string SubEmail { get; set; }
}

Layout view render partial view "_subscribe" which contain form to register to newsletter :

<body>
    <div id="container">
        <header>
            <div id="banner">
                @Html.Partial("~/Views/Soscom/_Subscribe.cshtml")
            </div>
        ....
</body>

my partial view "_Subscribe" :

@model SoscomAppMvc.Models.SubscribeModel

@using (Html.BeginForm("Subscribe", "Soscom"))
{
    @Html.TextBoxFor(m => m.SubEmail, new { placeholder = "Email pour s'inscrire à la newsletter", @class = "subscribebox", maxlength = "70" })
    @Html.ValidationMessageFor(m => m.SubEmail)
    <input class="subscribeBtn" type="submit" value="s'inscrire">
}

I use HttpGet Action method to send model to the partial view "_subscribe" :

    [HttpGet]
    public PartialViewResult Subscribe()
    {   
        return PartialView("_Subscribe", new SubscribeModel());
    }

but when I use an HttpPost Action below, I got a partial view without layout page?

    [HttpPost]
    public ActionResult Subscribe(SubscribeModel subscribe)
    {
        if (!ModelState.IsValid) 
            return PartialView("_Subscribe", subscribe);
        return View(subscribe);
    }

Questions:

is there a way to include the Post response in the current view?


Solution

  • Partials are just a way to reuse a bit of HTML in multiple views. Once the page is sent to the user and rendered in their browser, the fact that you had one or more partials on the page doesn't matter. If you do a traditional POST, it's going to change out the whole page because that's how things work.

    I think what you're trying to achieve is making a POST and only changing out a portion of the page, without prompting a full page reload. That requires AJAX. You'll need to catch and handle the submit event of the form with JavaScript, issue a POST request, with the serialized form data with AJAX, and finally replace some DOM node's content with the returned HTML on success.