2

I am attempting to render a partial view that contains a simple html form. I want to render the form from a controller as I handle the postback from an overloaded controller method. I have tried @Html.Action("ContactForm")but I get an Exception because child actions cannot redirect.

My Controller:

public ActionResult Index()
{
    return View();
}

[HttpGet]
public ActionResult ContactForm()
{
    return PartialView(new ContactForm()); 
}

[HttpPost]
public ActionResult ContactForm(ContactForm Contact)
{
    return RedirectToAction("FormResults", new { ContactForm = Contact });
}

public ActionResult FormResults(ContactForm Contact)
{
    return PartialView(Contact);
}

My Form:

@using(Html.BeginForm())
{
    <h2>Contact Form</h2>
    <div class="input-group">
        <h4>@Html.LabelFor(m => m.FirstName, "First Name")</h4>
        @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control", @placeholder = "First Name" })
    </div>
    <div class="input-group">
        <h4>@Html.LabelFor(m => m.LastName, "Last Name")</h4>
        @Html.TextBoxFor(m => m.LastName, new { @class = "form-control", @placeholder = "Last Name" })
    </div>
    <div class="input-group">
        <h4>@Html.LabelFor(m => m.Email, "Email")</h4>
        @Html.TextBoxFor(m => m.Email, new { @class = "form-control", @placeholder = "Email", @type = "text" })
    </div>

    <input type="submit" class="btn btn-info" value="Submit"  />
}

Any Help on how I would accomplish this would be appreciated.

2 Answers 2

1

try surrounding the form with a div and a certain id and use:

@using(Ajax.BeginForm("ContactForm","YourController",new AjaxOptions()
{
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "yourCertainId",
    HTTPMethod = "POST"
})

and your ActionMethod:

[HttpPost]
public ActionResult ContactForm(ContactForm Contact)
{
    return Partial("YourPartialName", Contact });
}

make sure that you include the bundle jqueryval on the bottom of your view.

you wont need the second controller method "FormResults"

Sign up to request clarification or add additional context in comments.

Comments

0

Does something like this not work for you?

I don't think you need a redirect.

[HttpPost]
public ActionResult ContactForm(ContactForm Contact)
{
    return PartialView("FormResults", Contact);
}

This uses the

PartialView(string viewName, object model) 

overload of the PartialView method in the Controller class.

This allows you to use a View that doesn't match the ActionResult's method name.

The same thing works for the plain "View" method as well.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.