Tom Stickel
Tom Stickel

Reputation: 20411

MVC (MVC3) checking is a Model exists or has values

I have created a working DropDownListFor which gets the data from a selectlist which is Model.IssueSocialSec and then setting the value coming from the database is Model.SocialDBValue

However, when I click a Edit link which with query a repository passing the Model back to the page, that works, but if I do a needed redirect route to the page and nothing is there to bind the Model, then the page fails. I'm going to try having it pass back an empty Model, but I figured I would post this as I always like to hear feedback on "best practices" and lessons learned.

 @Html.DropDownListFor(m => m.SelectedSocial, new SelectList(Model.IssueSocialSec, "Value", "Text", Model.SocialDBValue), "") 

Upvotes: 0

Views: 281

Answers (2)

Tom Stickel
Tom Stickel

Reputation: 20411

I ended up fixing it like this:

    ChildInfoModel childviewmodel = new ChildInfoModel();
    return View(childviewmodel);

before I was trying to just do: return View()

Upvotes: 0

Russ Cam
Russ Cam

Reputation: 125518

It sounds like you just need to wrap the DropDownListFor in a <form> with a url pointing to an action that will allow you to edit. The form can use a GET request if it's an idempotent operation and you could use JavaScript to submit the form when the value of the <select> is changed, falling back to rendering a button for submission for when JavaScript is disabled.

Generally, I structure MVC controllers and actions as so

public class ProfilesController : Controller
{
    public IProfileRepository Profiles { get; private set; }

    public ProfilesController(IProfilesRepository profiles)
    {
        Profiles = profiles;
    }

    [HttpGet]
    public ActionResult Index()
    {
        var profiles = Profiles.All();

        return View(new ProfilesModel { Profiles = profiles });
    }

    [HttpGet]
    public ActionResult Edit(int id)
    {
        var profile = Profiles.GetById(id);

        return View(new ProfileModel { Profile = profile });
    }

    [HttpPost]
    public ActionResult Edit(ProfileModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        var profile = Profiles.GetById(id);       

        // update the profile 
        Mapper.Map(model, profile);

        if (Profiles.Update(profile))
        {
            TempData["message"] = "Profile updated successfully";
        }

        return RedirectToAction("Edit");
    }
}

Index will render all the profiles. Against each profile, an <a> will be rendered with a URL pointing to Edit and the URL will include the id for the profile to edit. Edit view will post a form to Edit and the profile will be updated with changes from the model.

I recommend looking at something like NerdDinner or MVC Music store to get an idea of how they structure their code.

Upvotes: 1

Related Questions