Implementing edit action in asp.net mvc 3 - 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?

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.

Related

Is my MVC approach correct?

I'm writing an app in MVC 5 right now. I've made MVC app(for iOS) some time ago, but honestly i'm a little bit confused right now. I tried to find some info about this pattern, but it seems that there are many approaches.
My app uses external database operating on JSON format. I have bunch of methods in Api class that return objects filled with data from database. In my opinion this Api class is basically model, but i am not sure.
Model:
//Model
public class UserModel
{
public string Name { get; set; }
public string Lastname { get; set; }
}
Api class(Model?):
public class Api
{
public UserModel GetUserData()
{
UserModel model = new UserModel();
//code connecting to DB and filling UserModel object
return model;
}
}
Controller:
//Controller
public ActionResult Index ()
{
UserModel model = new UserModel();
Api api = new Api();
model = api.GetUserData();
return View(model);
}
View:
#*View*#
#model application.Models.UserModel
#Model.Name
#Model.Lastname
And my last question. Where should i put methods like loginuser, delete user:
public void DeleteUser(UserModel model)
{
//code deleting user
}
Should it go to model or controller? What i think is - if it will be used multiple times in different places i should put it in model, otherwise it should go to controller.
Thanks in advance.
Your Api class is not a model, the model classes must be entities of your domain. Your domain is the core of your business, for example, if your are making a School Application, your models/entities are: Student, Teacher, Discipline ...
So your Api belongs to your infrasctucture layer, and all classes with database access responsability.
Your controller's must only orchestrate the workflow, for example:
private readonly api;
public HomeController()
{
this.api = new Api();
}
public ActionResult Index ()
{
var model = api.GetUserData();
return View(model);
}
Your Api probably will be used on other Actions, so you can make a private field and initialize it from constructor. But the best approach is to use an IoC container.
The LoginUser must be a action on your Controller, but the business rule could be on other layer of your project, so it can be reusable. For example:
public ActionResult Login(string login, string password)
{
var user = api.GetUserByLogin(login);
if(user == null)
{
ViewBag.ErrorMsg = "There is no user with this login";
return View();
}
//userService is a class responsible for business rules for users
var isSuccess = userService.LoginUser(login, password);
if(isSuccess)
return RedirectToAction("Index", "Home");
ViewBag.ErrorMsg = "Password is incorrect";
return View();
}
Be careful because the ASP.NET MVC still have the concept of ViewModels. That are classes where we use to show data in our Views. In our school application, for example, we could have a View which is necessary to show a Discipline with all students enrolled, and what professor. So we need to use information of 3 entities, in that case we make a ViewModel to show all this information together.

ASP.Net Web API - How can I make it so that prefixes are not required when model binding from the query string?

In ASP.Net Web API (RC) I have a test model class like so:
[ModelBinder]
public class TestRequest
{
public string Foo { get; set; }
public string Bar { get; set; }
}
My controller looks like this:
public class TestController : ApiController
{
public TestRequest Get(TestRequest model)
{
return model;
}
}
Now if I invoke the action via:
http://.../test?foo=abc&bar=xyz
neither values bind, because the model binder is expecting model prefixes, such that I actually need to call:
http://.../test?model.foo=abc&model.bar=xyz
I can understand that this is so that other action parameters can bind correctly, but in my case the model is a clean way of encapsulating all the possible action parameters so that I don't need to have a nasty action method signature with a whole lot of optional parameters. It also allows for easy model validation.
Is there any easy way to cause model binding to behave the same way as it would in MVC, or in a POST request?
Removing the ModelBinder attribute from your model class should work in the example you've posted. You'll run into issues for more complex method signatures, see Rick Strahl's comment: http://blogs.msdn.com/b/jmstall/archive/2012/04/16/how-webapi-does-parameter-binding.aspx#10302750

MVC Code First C# Retrieve Data

Ok So I am just simply needing good instructional pages on how to design a Class for retrieving data from the database.
I can find information all over on how to take an existing database and create an Entity Framework from it but I am trying to do code first.
I am able to insert Data (although I am not 100% sure how that is working) I just cannot seem to figure out how to pull the data from the database using the class(Model) that is created and display that data on a Razor page.
I have no problem with doing the studying and learning this but I am having a terrible time at finding good information that will just do a true walk through of this process.
Once again I am not looking for the Entity Framework.
Thank you for all of the help you can provide.
There is a lot of tutorials out there in the internet. Here is a small example to pull your data from table and show in the view.
Assuming you have a model class called User like this
public class User
{
public int ID { set;get;}
public string FirstName { set;get;}
}
Add properties like this to your DataContext class for each of your model entities. The property is of type DbSet.
public class YourDataContext: DbContext
{
public DbSet<User> Users {set;get;}
}
Then in your controller action method, you can create an instance of your DBContext class and access its Users property. Pass that to our view.
public class UserController : Controller
{
public ActionResult Index()
{
YourDBContext db=new YourDBContext();
var users=db.Users.ToList();
return View(users)
}
}
Have an index.cshtml view like this under Views/User folder.
#model IEnumerable User
#foreach(var user in Model)
{
<p>#user.FirstName</p>
}

MVC 3 split parameters in HttpPost action

I have an MVC 3 app and I have created a generic wrapper object, which has some navigation properties and the wrapped object of T, whose values I'm editing/displaying.
public class NavigationViewModel<T>
{
public T Model { get; set; }
public NavigationHelper NavigationHelper { get; set; }
public NavigationViewModel() { }
public NavigationViewModel(T model, NavigationHelper helper)
{
this.Model = model;
this.NavigationHelper = helper;
}
}
My controller resolves this object nicely in an action like this:
public ActionResult Foo(NavigationViewModel<Bar> viewModel)
Code in my view looks like this:
#Html.EditorFor(model => model.Model.SomeProperty)
My colleague said that that code is not nice to read. I already have a strongly typed view, the Model and this Model has another property called Model. He suggested to rename the Model property to ViewModel and I agreed with his reasoning.
Now, the code with the renamed properties does not work anymore: NavigationViewModel viewModel is null. So I changed the signature of the HttpPost method to the following and it works again:
[HttpPost]
public ActionResult Foo(NavigationHelper helper, Bar viewModel)
I like this very much! I can directly access my viewModel in code, the code in the view makes sense and the helper object does not get in the way. I haven't seen this convention before and I guess it worked before because of the naming convention. Using a property called Model hinted at how to resolve the object. Without that property, it couldn't resolve it anymore.
I would like to adopt this for other kinds of helpers that contain view-specific properties, like select-lists or other properties that I otherwise might have put in my ViewBag. Would you guys recommend this approach or will I run into trouble later on using this?
I think I have a really simple answer for you, just don't name your action parameter viewModel, so change:
public ActionResult Foo(NavigationViewModel viewModel)
public ActionResult Foo(NavigationViewModel model)
Or any other parameter name that does not collide with your ViewModel property on your NavigationViewModel class.

How to bypass validation when using viewmodels for search filtering in ASP.NET MVC (3RC2)

I'm working on an ASP.NET MVC app (using MVC3 RC2). Say I have 2 entities, Product and Category. A Category must have a CategoryTitle, which is denoted via metamodel attributes like so:
public class CategoryModel
{
public int CategoryID { get; set; }
[Required("{0} is required.")]
public int CategoryTitle { get; set; }
}
There is also a relationship such that each Product has an association with Category. When searching Products, users must be able to filter the results by selecting a Category from a drop-down HTML select list. I've tried different ways of doing this, and the following seems to promote the most code reuse:
public class SearchModel
{
public CategoryModel Category { get; set; }
public string Keyword { get; set; }
}
public class ProductController
{
public ActionResult Search(SearchModel searchModel)
{
if (ModelState.IsValid)
{
// logic to return view with viewmodel
}
return HttpNotFound();
}
}
In the view, a drop-down list is rendered using the SearchModel, and it sends requests via HTTP GET in the form of /Product/Search?Keyword=my+keywords&Category.CategoryID=69. The SearchModel object is populated as intended, creating a new CategoryModel with CategoryID == 69.
The problem is that the ModelState.IsValid always returns false, since the Category.Title is null. What is the appropriate way to do this in ASP.NET MVC? Do I have to resort to creating a different SearchModel that doesn't have a CategoryModel instance?
The proper way to do this is to use view models instead of your models to and from the views. View models are classes which are specifically tailored to the needs of a given view: they contain only the properties required for the view and the validation attributes in the context of the given view. Thus you might have multiple view models for the same model. To map between the model and the view models you could use AutoMapper.

Resources