MVC and the disappearing menu bar

In my marvelous edit user form, I had a partial view appearing at the top of my page, and outside of the form, like so:

@Html.Partial("~/Views/Shared/_LoginPartial.cshtml")
@using (Html.BeginForm("UserStuff", "Account", FormMethod.Post)) {
        <select id="users" name="users" onchange="getUser()">
            <option selected="selected" value="0">Add User</option>
        </select>
 Plenty of fields…
        <input type="submit" id="save" value="Save" />
}

I had modified the default _LoginPartial.cshtml file, adding a couple of links to the mix. Here is an abbreviated view of the view:

@model MvcSecurity.Models.UserProfile
@using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm" })) {
    if (Model != null) {
        <span style="float: left">
            @Html.ActionLink("One", "One", "Home") |
            @Html.ActionLink("Two", "Two", "Home")
        </span>
        <a href="javascript:document.getElementById('logoutForm').submit()">Log off</a>
    }
}

All was good until I actually, you know, used the page. Then, my marvelous partial view would disappear, like a dollar bill from your pocket when a politician is nearby.

The problem lay in my not-so-marvelous controller action. When good stuff happened, the record would be saved, but my partial view would disappear. The code in question:

public ActionResult UserStuff (UserProfile model) {
          if (goodStuffHappened > 0) {
                       ModelState.Clear();
          } else {
                       ModelState.AddModelError("", "Bad!");
                       return View(model);
          }
          return View();
}

I’m sure, observant reader, you can pick up where I went wrong. My partial view was bound to the UserProfile model, but there was no model being assigned to the view. Thus, the line in the partial view where it checks to see if the model was true always failed, and all my exquisite links were gone.

To fix it, I made sure that when good stuff happened, the model was returned:

public ActionResult UserStuff (UserProfile model) {
            if (goodStuffHappened > 0) {
                     ModelState.Clear();
                     return View(user);
            } else {
                     ModelState.AddModelError("", "Bad!");
                     return View(model);
            }
            return View();
}
Advertisements

,

  1. Leave a comment

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

%d bloggers like this: