ctb
ctb

Reputation: 131

MVC 3 - Posting partial view to a chosen controller

I'm trying to learn MVC 3 and Razor coming from a ASP.NET background.

I've want to get a simple partial view (in the shared folder) to post to a specific controller so that I can re-use it elsewhere such as for articles, blogs etc. I tried using variations of the following.

@using (Html.BeginForm("Create", "Comment", FormMethod.Post,  new { }))
{
    <div>
        <fieldset>
            <legend>Comments</legend>

            <div >
                @Html.LabelFor(m => m.Name)
                @Html.TextBoxFor(m => m.Name)              
            </div>

            <div >
                @Html.LabelFor(m => m.Email)
                @Html.TextBoxFor(m => m.Email)              
            </div>

            <div >
                @Html.LabelFor(m => m.Body)
                @Html.TextBoxFor(m => m.Body)              
            </div>

            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    </div>
}

This doesn't post to the comments controller action Create as shown below.

[HttpPost]
public ActionResult Create()
{
    // Save comment code here

    return View();
}

There is any simple way of doing this without having to bound to a specfic route?

Upvotes: 0

Views: 3687

Answers (1)

ctb
ctb

Reputation: 131

I found the answer.

@using (Ajax.BeginForm("Create", "Comment",  new AjaxOptions() {
        UpdateTargetId = "MainContainer"    })) 
{ 
     <div>
        <fieldset>
            <legend>Comments</legend>

            <div >
                @Html.LabelFor(m => m.Name)
                @Html.TextBoxFor(m => m.Name)              
            </div>

            <div >
                @Html.LabelFor(m => m.Email)
                @Html.TextBoxFor(m => m.Email)              
            </div>

            <div >
                @Html.LabelFor(m => m.Body)
                @Html.TextBoxFor(m => m.Body)              
            </div>

            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    </div>
}

This posts back using ajax and doesn't change the URL. Or you can do it this way using JQuery http://jvance.com/blog/2010/02/20/MakingAnAjaxFormWithJQueryInASPdotNETMVC.xhtml

Upvotes: 1

Related Questions