开发者

Problem organizing code in asp.net MVC 2

开发者 https://www.devze.com 2023-02-07 04:02 出处:网络
I\'m new to MVC and I borrow a book from library yesterday on asp.net MVC 2. I\'m a bit confused about what kind of code should be included in Model, view and controller.I was working on开发者_JS百科

I'm new to MVC and I borrow a book from library yesterday on asp.net MVC 2.

I'm a bit confused about what kind of code should be included in Model, view and controller. I was working on开发者_JS百科 user input validation from the book and if I understand correctly, it seems they declare variables in "Model", validating user input in "Controller" and display the web page in "View".

Model: -Declaring variables

e.g: 
class Contact:
public string Name { get; set; }
public string EmailAddress { get; set; }

Views: -Contain HTML, HTML Helper code, displaying contents and use variables from "Model"

e.g: 
<%: Html.TextBoxFor(model => model.Name) %>
<%: Html.ValidationMessageFor(model => model.Name) %>

Controller: -"Playing"/"Manipulating" variables from Model + Call "View" to display web page at the end (return View()). (Validating user input for this example)

e.g:
if (String.IsNullOrEmpty(contact.Name))
   ModelState.AddModelError("Name", "Please enter your name.");

I'm not sure but it seems to me that "Controller" is the "heavy coding" part to me. On the other hand, "View" is the good old HTML, markup that display the web site and "Model" is a place that store data (declaring variables for example.)

Please let me know whether I'm on the right direction. Thanks :)


I'm not sure but it seems to me that "Controller" is the "heavy coding" part to me

You should avoid having fat controllers. In fact the controller might depend on a service layer which contains the business logic of you application. This service layer could itself depend on repositories performing the data access (simple CRUD operations) on the models. So the controller would simply invoke a business operation call on the service layer to fetch/update the model and then pass a view model to the view in order to display it.


I am also new to MVC and first thing i did when i started was to view most of the talks given by Scott Hanselman and Phill Haack. So you might try this one: [http://channel9.msdn.com/blogs/matthijs/aspnet-mvc-2-basics-introduction-by-scott-hanselman][1]

[1]: http://channel9.msdn.com/blogs/matthijs/aspnet-mvc-2-basics-introduction-by-scott-hanselman to get started. From what i got so for, Darin is right. Try to avoid fat controllers and work with a repository for your model. Also, I noticed that for simple validation (required, maximum string length and such) it is preferred to use DataAnnotion on the model... So your Contact model might look like this:

class Contact:
[Required]
public string Name { get; set; }
public string EmailAddress { get; set; }

This will make the Name property required on Edit/Create Views.

0

精彩评论

暂无评论...
验证码 换一张
取 消