I have a partial view that can be called from anywhere on my website. When the user clicks a submit button in the Partial View an email is sent. The user is not asked for any information as this is already contained in my Model. The C# code is in my Partial View rather than my Controller as I needed to pass the Model (which contains several arrays) as a parameter but was unsuccessful doing so. When the user clicks the button, the form submits and the mail sends but then the user is redirected to the address of the Partial View, rather than the address of the original View with the Partial View displayed. How can I prevent this redirection?

For example if PartialView.cshtml is loaded from /Home/View/ I am redirected to /Home/PartialView on post.

PartialView.cshtml loaded from HomeController.cs via Ajax post in JQuery

[HttpPost]
public ActionResult PartialView()
{
    ....create myModel....
    return PartialView(myModel);
}

PartialView.cshtml

@using (Html.BeginForm()) { 
    <input type="submit" value="email" />
}

...rest of partial view...

@{
    if (IsPost){
        ....sends email using data in model....
    }
}

Previously I had the following, but the data in the model received by the controller was always null. (not part of the question but in case someone asks why my code is not in my controller):

PartialView.cshtml

@using (Html.BeginForm("sendMail", "Home",  FormMethod.Post, new { myModel = Model }))
{
    @Html.HiddenFor(a => a.firstArray);
    @Html.HiddenFor(a => a.secondArray);
    <input type="submit" value="email" />
}

HomeController.cs

[HttpPost]
public void sendMail(myModelType myModel )
{
    ....send email using data in model....
}

Related posts

Recent Viewed