yaegerbomb
yaegerbomb

Reputation: 1188

PartialView form validation then calling a controller method in MVC3

I am very new to MVC3 and having problems wrapping my head around things. Right now I have a partial view which I have simplified below:

@model blah.blah.blah.blah.ForumPost

@using (Html.BeginForm()) {

<fieldset>
    <legend>ForumPost</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.ForumID)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.ForumID)
        @Html.ValidationMessageFor(model => model.ForumID)
    </div>
    <p>
        <input type="submit" value="Create" />
        @Html.ValidationSummary(true)
    </p>
</fieldset>

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
}

I am not what to do for form validation. I have been trying to using jquery validation but I cant seem to find a good example that fits what I am doing and just get lost. I was basing it off this example here but it isn't enough.

After I am done I want to call a method in some code and I am not really sure of a clean way to do this. The way I have it currently working is using an ajax call and it's really ugly. Also a colleague suggested I pass the method an actual forum post but I don't know how. The code for the method I want to call is below:

public void PostToForum(ForumPost post)
{
    UserService cu = new UserService();
    int PostUserID = cu.GetUserIDByUsername(base.User.Identity.Name);

    if (this.ModelState.IsValid)
    {
        ForumPost nfp = service.CreateForumPost(post);
    }
}

Anyone have some tips? Thanks.

I can provide more code if it's necessary.

Upvotes: 1

Views: 498

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039538

Html forms are usually submitted to controller actions:

[HttpPost]
public ActionResult Create(ForumPost model)
{
    if (!ModelState.IsValid)
    {
        // validation failed => redisplay the view so that the user can fix the errors
        return View(model);
    }

    // at this stage the model is valid => process it:
    service.CreateForumPost(model);

    return ...
}

Now since this is a partial view you must be careful with the view you are returning from this controller action as well as the model. If you don't use AJAX you should return the entire parent view and the parent view model. If you use an AjaxForm then you could only work with the partial model and view. Also in this case in the event of success you could return a Json result to the view to indicate this success so that the javascript handler that will be executed could take the respective actions.

Upvotes: 2

Related Questions