Manipulating other elements when ModelState is not valid

Is it possible to change the class on another element when !ModelState.IsValid?

My view, simplified below, will have <div class="control"> wrapped around each <input> field

@using(Html.BeginForm("AddRole","Admin", FormMethod.Post, new { @class = "ajax" })) {
    <div class="control">
        @Html.TextBoxFor(x => x.Role, new { @class = "input-xlarge", @placeholder = Html.DisplayNameFor(x => x.Role)})
        @Html.ValidationMessageFor(x => x.Role)
    </div>
}

$(function () {
    $('form.ajax').submit(function () {
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                if (result.success) {
                    location.reload(true);
                } else {
                    $(this).html(result);
                }
            }
        });
        return false;
    });
});

and my controller...

[HttpPost]
public ActionResult AddRole(RoleModel model) {
    if(!ModelState.IsValid) {
        return PartialView("_AddRolePartial", model);
    }
    try {
        System.Web.Security.Roles.CreateRole(model.Role);
        return Json(new {success = true});
    } catch(Exception) {
        ModelState.AddModelError("", "Role creation unsuccessful.");
    }

    return PartialView("_AddRolePartial", model);
}

I would like to be able to add the class error to div.control for any property in the model that isn't valid. I think I could handle this through jQuery in the ajax success event but perhaps there's a better solution all together.

Answers


What you are trying to achieve would introduce coupling between your controller and your view, and this is fundamentally against the idea behind MVC (separation of concern). Your controller should not know anything about your view, so I would strongly suggest you do this with jQuery/javascript in the view. Just return a viewbag that contains names of your invalid properties and use jquery to add the error class.


Need Your Help

Why this WinSock code is not connecting to client?

c++ c visual-c++ winsock2 winsockets

I am new to Winsock programming and came across this code while reading the book "Network Programming For Microsoft Windows " . But it seems that this code is not able to connect to the client. Ple...

Play Framework Error on BindRequest

java controller playframework-2.0

I'm getting the following error on Play 2.1.3: