Adding Forms to umbraco using Surface Controller

Step I: Create an empty mvc project in visual studio
Step II: Add the required model to models folder. Here we create a model named StudentModel as shown below


public class StudentModel
{
    public string FullName { get; set; }
}

Step III: Add controller to the controllers project. Here we add the controller named StudentSurfaceController. Note that the name of the controller should be same as the name of the document type and suffixed with SurfaceController.


public class StudentSurfaceController : SurfaceController
{   
    public ActionResult RenderStudentForm()
    {
        return PartialView("StudentForm",new MVCUserControl.Models.StudentModel());
    }
    [HttpPost]
    public ActionResult HandleStudentForm(MVCUserControl.Models.StudentModel student)
    {
        if (!ModelState.IsValid)
        {
            //Not valid - so lets return the user back to the view with the data they entered still prepopulated
            return CurrentUmbracoPage();
        }
        return RedirectToCurrentUmbracoPage();
    }
}

HandleStudentForm handles the post request after form is submitted.
Step IV: Build the project and add the dll to bin folder in umbraco
Step V: Now we need to create a partial view and add it to the template. Here we create a partial view StudentPartial.cshtml and add it to student template.


@using MVCUserControl.Controllers
@using MVCUserControl.Models
@model StudentModel

@using (Html.BeginUmbracoForm("HandleStudentForm"))
{
    @Html.TextBoxFor(model => model.FullName, new { placeholder = "Your Name" })
    <input type="submit" value="Send" />
}

Step VI: Render the partial view


@{
    Html.RenderPartial("StudentPartial", new MVCUserControl.Models.StudentModel() { FullName=Model.Content.GetPropertyValue("fullName")});
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s