Alexandre
Alexandre

Reputation: 13308

Implementing edit action in asp.net mvc 3

I seen many examples of edit actions in asp.net mvc 3 and that's why I confused. For example, how does work UpdateModel and TryUpdateModel methods? Or how to implement edit action if I want to update not all fields?

Could anyone give me a link about implementing edit action in asp.net 3?

Upvotes: 0

Views: 707

Answers (1)

archil
archil

Reputation: 39491

Best way to update only desired fields is create separate view model for it. For example, imagine you've got user class like this

public class User
{
     public int Id {get;set;}
     public string UserName {get;set}
     public bool IsAdmin {get;set;}
}

And suppose you do not wish to let user supply value for IsAdmin property. You create view model like this (no IsAdmin field)

public class EditUserViewModel
{
     public int Id {get;set;}
     public string UserName {get;set}
}

And the edit action pseudo something

public ActionResult Edit(EdituserViewModel model)
{
     If(ModelState.IsValid)
     {
        User user = _repository.GetUser(model.Id);
        user.UserName = model.UserName;
        _repository.Update(user);
        return RedirectToAction("Index");
     }
     return View(model);
}

This way, there's no possiblity to supply IsAdmin from client side. You may also want to take a look at AutoMapper and Jimmy Bogard's blog for mapping view models to domain models. Jimmy's got the post about using ViewModels and AutoMapper in asp.net mvc too.

Upvotes: 1

Related Questions