• mvc杂记


    ASP.NET MVC2 in Action 读书笔记 [1]

    Chapter01:

    1). GuestBook

    Index.aspx:

    <form method="post" action="/GuestBook/Sign">
        <fieldset>
            <legend>Guest Book</legend>
            
            <%= Html.Label("Name") %>
            <%= Html.TextBox("Name") %>
            
            <%= Html.Label("Email") %>
            <%= Html.TextBox("Email") %>
            
            <%= Html.Label("Comments") %>
            <%= Html.TextArea("Comments", new { rows=6, cols=30 }) %>
            
            <div>
            <input type="submit" value="Sign" />
            </div>
        </fieldset>
        </form>

    ThankYou.aspx:

    <h2>Thank You!</h2>
        <p>Thank you for signing the guest book!  You entered:</p>
        Name: <%= ViewData["name"] %><br />
        Email: <%= ViewData["email"] %><br />
        Comments: <i><%= ViewData["comments"] %></i>

    GuestBookController.cs:

    public class GuestBookController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
     
            public ActionResult Sign(string name, string email, string comments)
            {
                //do something with the values, such as send an email
     
                ViewData["name"] = name;
                ViewData["email"] = email;
                ViewData["comments"] = comments;
     
                return View("ThankYou");
            }
        }

     

    2).GuestBookWithModel

    Index.aspx:

    <h2>Sign the Guest Book!</h2>
        
        <% using (Html.BeginForm()) {%>
     
            <fieldset>
                <legend>Fields</legend>
                <p>
                    <%= Html.LabelFor(model => model.Name) %>
                    <%= Html.TextBoxFor(model => model.Name) %>                
                </p>
                <p>
                    <%= Html.LabelFor(model => model.Email) %>
                    <%= Html.TextBoxFor(model => model.Email) %>                
                </p>
                <p>
                    <%= Html.LabelFor(model => model.Comments) %>
                    <%= Html.TextAreaFor(model => model.Comments) %>                
                </p>
                <p>
                    <input type="submit" value="Create" />
                </p>
            </fieldset>
     
        <% } %>    

    ThankYou.aspx:

    <h2>Thank You!</h2>
        
        Thank you for signing our Guest Book.  You entered: <br />
        
        <%= Html.DisplayForModel() %>

    GuestBookController.cs:

    public class GuestBookController : Controller
        {
            public ActionResult Index()
            {
                var model = new GuestBookEntry();
                return View(model);
            }
     
            [HttpPost]
            public ActionResult Index(GuestBookEntry entry)
            {
                //hang on to the submitted value, so we can
                //retrieve it upon redirect
                TempData["entry"] = entry;
                return RedirectToAction("ThankYou");
            }
     
            public ActionResult ThankYou()
            {
                if(TempData["entry"] == null)
                {
                    //somehow they got here without filling out the form
                    return RedirectToAction("index");
                }
     
                var model = (GuestBookEntry) TempData["entry"];
                return View(model);
            }
        }

    GuestBookEntry.cs:

    public class GuestBookEntry
        {
            public string Name { get; set; }
            public string Email { get; set; }
            public string Comments { get; set; }
        }

     

     

    ASP.NET MVC2 in Action 读书笔记 [2]

    Chapter02:

    1). InputModel

    New.aspx:

    <h2>New Customer</h2>
        <form action="<%= Url.Action("Save") %>" method="post">
            <fieldset>
                <div>
                    <%= Html.LabelFor(x => x.FirstName) %> 
                    <%= Html.TextBoxFor(x => x.FirstName) %>
                </div>
                <div>
                    <%= Html.LabelFor(x => x.LastName) %> 
                    <%= Html.TextBoxFor(x => x.LastName) %>
                </div>
                <div>
                    <%= Html.LabelFor(x => x.Active) %> 
                    <%= Html.CheckBoxFor(x => x.Active) %></div>
                <div>
                <button name="save">Save</button></div>    
            </fieldset>
        </form>

    Save.aspx:

    <h2>Customer</h2>
        <div>
            Customer was saved.
        </div>
        <div>First Name: <%= Model.FirstName %></div>
        <div>Last Name: <%= Model.LastName %></div>
        <div>Active: <%= Model.Active %></div>

    CustomerController.cs:

    public class CustomerController : Controller
        {
            public ViewResult New()
            {
                return View();
            }
     
            public ViewResult Save(NewCustomerInput input)
            {
                return View(input);
            }
        }

    NewCustomerInput.cs:

    public class NewCustomerInput
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public bool Active { get; set; }
        }

     

    2). DisplayModel

    Index.aspx:

    <h2>Customer Summary</h2>
        <table>
             <tr>
                  <th>Name</th>
                  <th>Active?</th>
                  <th>Service Level</th>
                  <th>Order Count</th>
             <th>Most Recent Order Date</th>
             </tr>
             <% foreach (var summary in Model) { %>
                    <tr>
                        <td><%= summary.Name %></td>
                        <td><%= summary.Active ? "Yes" : "No" %></td>
                        <td><%= summary.ServiceLevel %></td>
                        <td><%= summary.OrderCount %></td>
                        <td><%= summary.MostRecentOrderDate %></td>
                    </tr>
             <% } %>
        </table>

    CustomerSummaryController.cs:

    public class CustomerSummaryController : Controller
        {
            private readonly CustomerSummaries _customerSummaries = new CustomerSummaries();
     
            public ViewResult Index()
            {
                IEnumerable<CustomerSummary> summaries =
                    _customerSummaries.GetAll();
     
                return View(summaries);
            }
        }

    CustomerSummaries.cs:

    public class CustomerSummaries
        {
            public IEnumerable<CustomerSummary> GetAll()
            {
                return new[]
                           {
                               new CustomerSummary
                                   {
                                       Active = true,
                                    Name = "John Smith",
                                       MostRecentOrderDate = "02/07/10",
                                       OrderCount = "42",
                                       ServiceLevel = "Standard"
                                   },
                               new CustomerSummary
                                   {
                                       Active = false,
                                       Name = "Susan Power",
                                       MostRecentOrderDate = "02/02/10",
                                       OrderCount = "1",
                                       ServiceLevel = "Standard"
                                   },
                               new CustomerSummary
                                   {
                                       Active = true,
                                       Name = "Jim Doe",
                                       MostRecentOrderDate = "02/09/10",
                                       OrderCount = "7",
                                       ServiceLevel = "Premier"
                                   },
                           };
            }
        }

    CustomerSummary.cs:

    public class CustomerSummary
        {
            public string Name { get; set; }
            public bool Active { get; set; }
            public string ServiceLevel { get; set; }
            public string OrderCount { get; set;}
            public string MostRecentOrderDate { get; set; }
        }

     

    3). ComboModel

    Index.aspx:

    <h2>Customer Summary</h2>
        <form action="<%= Url.Action("Save") %>" method="post">
         <table>
              <tr>
                  <th>Name</th>
                  <th>Service Level</th>
                  <th>Order Count</th>
                  <th>Most Recent Order Date</th>
                  <th>Active?</th>
              </tr>
              
              <% int index = 0; foreach (var summary in Model) { %>
              
                  <tr>
                        <td><%= summary.FirstName %> <%= summary.LastName %></td>
                        <td><%= summary.ServiceLevel %></td>
                        <td><%= summary.OrderCount %></td>
                        <td><%= summary.MostRecentOrderDate %></td>
                        <td>
                            <%= Html.CheckBox("input[" + index + "].Active", summary.Input.Active) %>
                            <input type="hidden" value="<%= summary.Input.Number %>" name="<%= "input[" + index + "].Number" %>" value="<%= summary.Input.Number %>" />
                        </td>
                  </tr>
              
              <% index++; } %>
              
         </table>
         <button name="submit">Change Status</button>
         </form>

    Save.aspx:

    <h2>Saved Customers</h2>
        
        <% foreach (var input in Model) { %>
            <div>
                Customer number <%= input.Number %> is <%= input.Active? "Active" : "Inactive" %>
            </div>
        <% } %>

    CustomerSummaryController.cs:

    public class CustomerSummaryController : Controller
        {
            private readonly CustomerSummaries _customerSummaries = new CustomerSummaries();
     
            public ViewResult Index()
            {
                IEnumerable<CustomerSummary> summaries =
                    _customerSummaries.GetAll();
     
                return View(summaries);
            }
     
            public ViewResult Save
                (List<CustomerSummary.CustomerSummaryInput> input)
            {
                return View(input);
            }
        }
     
        public class CustomerSummaries
        {
            public IEnumerable<CustomerSummary> GetAll()
            {
                return new[]
                           {
                               new CustomerSummary
                                   {
                                       Input = new CustomerSummary.CustomerSummaryInput {Active = true, Number = 4},
                                       FirstName = "John",
                                       LastName = "Smith",
                                       MostRecentOrderDate = "02/07/10",
                                       OrderCount = "42",
                                       ServiceLevel = "Standard"
                                   },
                               new CustomerSummary
                                   {
                                       Input = new CustomerSummary.CustomerSummaryInput {Active = false, Number = 5},
                                       FirstName = "Susan",
                                       LastName = "Power",
                                       MostRecentOrderDate = "02/02/10",
                                       OrderCount = "1",
                                       ServiceLevel = "Standard"
                                   },
                               new CustomerSummary
                                   {
                                       Input = new CustomerSummary.CustomerSummaryInput {Active = true, Number = 6},
                                       FirstName = "Jim",
                                       LastName = "Doe",
                                       MostRecentOrderDate = "02/09/10",
                                       OrderCount = "7",
                                       ServiceLevel = "Premier"
                                   },
                           };
            }
        }

    CustomerSummary.cs:

    public class CustomerSummary
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string ServiceLevel { get; set; }
        public string OrderCount { get; set; }
        public string MostRecentOrderDate { get; set; }
     
        public CustomerSummaryInput Input { get; set; }
     
        public class CustomerSummaryInput
        {
            public int Number { get; set; }
            public bool Active { get; set; }
        }
    }

     

     

     

    ASP.NET MVC2 in Action 读书笔记 [3]

    Chapter03:

    AccountProfile

    Index.aspx:

    <h2>Profiles</h2>
        <table>
            <tr>
                <th>Username</th>
                <th>First name</th>
                <th>Last name</th>
                <th>Email</th>
                <th>&nbsp;</th>
            </tr>
            <% foreach (var profile in Model) { %>
            <tr>
                <td>
                    <%= Html.Encode(profile.Username) %>
                </td>
                <td>
                    <%= Html.Encode(profile.FirstName) %>
                </td>
                <td>
                    <%= Html.Encode(profile.LastName) %>
                </td>
                <td>
                    <%= Html.Encode(profile.Email) %>
                </td>
                <td>
                    <%= Html.ActionLink("View Profile", "Show", new{username = profile.Username}) %>
                </td>
            </tr>
            <% } %>
        </table>

    Show.aspx:

    <h2>
            View Profile</h2>
        <fieldset>
            <legend>Fields</legend>
            <p>
                Username:
                <%= Html.Encode(Model.Username) %>
            </p>
            <p>
                FirstName:
                <%= Html.Encode(Model.FirstName) %>
            </p>
            <p>
                LastName:
                <%= Html.Encode(Model.LastName) %>
            </p>
            <p>
                Email:
                <%= Html.Encode(Model.Email) %>
            </p>
        </fieldset>
        <p>
            <% 
                bool hasPermission = (bool)ViewData["hasPermission"];
                if (hasPermission)
                { %>
            <%=Html.ActionLink("Edit", "Edit", new { username = Model.Username }) %>
            |
            <%=Html.ActionLink("Back to List", "Index") %>
            <% } %>
        </p>

    Edit.aspx:

    <h2>Edit</h2>
     
        <% using (Html.BeginForm()) {%>
        
            <%= Html.EditorForModel() %>
            <p>
                <button type="submit" value="Save" name="SaveButton">Save</button>
                <button type="submit" value="SaveAndClose" name="SaveButton">Save and Close</button>
            </p>
     
        <% } %>
     
        <div>
            <%=Html.ActionLink("Back to List", "Index") %>
        </div>

    ProfileModels.cs:

    public class Profile
        {
            public Profile(string username)
            {
                Username = username;
            }
     
            public string Username { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Email { get; set; }
        }
     
        public class ProfileEditModel
        {
            public ProfileEditModel(Profile profile)
            {
                Username = profile.Username;
                FirstName = profile.FirstName;
                LastName = profile.LastName;
                Email = profile.Email;
            }
     
            public ProfileEditModel()
            {
            }
     
            public string Username { get; set; }
     
            [DisplayName("First Name")]
            public string FirstName { get; set; }
     
            [DisplayName("Last Name")]
            public string LastName { get; set; }
     
            public string Email { get; set; }
        }
     
        public interface IProfileRepository
        {
            Profile[] GetAll();
            Profile Find(string username);
            void Add(Profile profile);
        }
     
        public class ProfileRepository : IProfileRepository
        {
            private static List<Profile> _profiles = new List<Profile>();
     
            static ProfileRepository() {
                _profiles.Add(new Profile("JPalermo") { FirstName = "Jeffrey", LastName = "Palermo", Email = "jeffrey@MVC2Demo.example" });
                _profiles.Add(new Profile("BScheirman") { FirstName = "Ben", LastName = "Scheirman", Email = "ben@MVC2Demo.example" });
                _profiles.Add(new Profile("MHinze") { FirstName = "Matt", LastName = "Hinze", Email = "matt@MVC2Demo.example" });
                _profiles.Add(new Profile("JBogard") {  FirstName = "Jimmy", LastName = "Bogard", Email = "jimmy@MVC2Demo.example" });
                _profiles.Add(new Profile("EHexter") { FirstName = "Eric", LastName = "Hexter", Email = "eric@MVC2Demo.example" });
     
            }
     
            public Profile[] GetAll()
            {
                return _profiles.ToArray();
            }
     
            public Profile Find(string username)
            {
                var profile = _profiles.FirstOrDefault(p => p.Username == username);
                if (profile == null)
                {
                    profile = new Profile(username);
                    Add(profile);
                }
     
                return profile;
            }
     
            public void Add(Profile profile)
            {
                _profiles.Add(profile);
            }
        }

    ProfileController.cs:

    public class ProfileController : Controller
        {
            private readonly IProfileRepository _profileRepository;
     
            public ProfileController(IProfileRepository profileRepository)
            {
                _profileRepository = profileRepository;
            }
     
            public ProfileController() : this(new ProfileRepository()) { }
     
            public ViewResult Index()
            {
                var profiles = _profileRepository.GetAll();
                return View(profiles);
            }
     
            public ViewResult Show(string username)
            {
                var profile = _profileRepository.Find(username);
     
                bool hasPermission = User.Identity.Name == username;
     
                ViewData["hasPermission"] = true;
     
                return View(profile);
            }
     
            public ViewResult Edit(string username)
            {
                var profile = _profileRepository.Find(username);
                return View(new ProfileEditModel(profile));
            }
     
            public RedirectToRouteResult Save(ProfileEditModel form)   ??????????? 正确吗????
            {
                var profile = _profileRepository.Find(form.Username);
     
                profile.Email = form.Email;
                profile.FirstName = form.FirstName;
                profile.LastName = form.LastName;
     
                return RedirectToAction("Index");
            }
     
        }

     

    ASP.NET MVC2 in Action 读书笔记 [4]

    Chapter04:

    ControllerExamples

    Index.aspx:

    <h2>Index</h2>
        <%if (TempData.ContainsKey("message"))
          {%>
        <p class="input-validation-success"><%=TempData["message"]%></p>
        <%} %>
        <table>
            <tr>
                <th>
                    Username
                </th>
                <th>
                    Name
                </th>
            </tr>
     
        <% foreach (var item in Model) { %>
        
            <tr>
                <td>
                    <%= Html.Encode(item.Username) %>
                </td>
                <td>
                    <%= Html.Encode(item.Name) %>
                </td>
            </tr>
        
        <% } %>
     
        </table>

    Display.aspx:

    <h2>Display</h2>
     
        <fieldset>
            <legend>Fields</legend>
            <p>
                Username:
                <%= Html.Encode(Model.Username) %>
            </p>
            <p>
                Name:
                <%= Html.Encode(Model.Name) %>
            </p>
        </fieldset>

    Edit.aspx:

    <h2>Edit</h2>
     
     
        <% using (Html.BeginForm()) {%>
            <%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>
     
            <fieldset>
                <legend>Fields</legend>
                <p>
                    <label for="Username">Username:</label>
                    <%= Html.TextBox("Username", Model.Username) %>
                    <%= Html.ValidationMessage("Username", "*") %>
                </p>
                <p>
                    <label for="FirstName">FirstName:</label>
                    <%= Html.TextBox("FirstName", Model.FirstName) %>
                    <%= Html.ValidationMessage("FirstName", "*") %>
                </p>
                <p>
                    <label for="LastName">LastName:</label>
                    <%= Html.TextBox("LastName", Model.LastName) %>
                    <%= Html.ValidationMessage("LastName", "*") %>
                </p>
                <p>
                    <input type="submit" value="Save" />
                </p>
            </fieldset>
     
        <% } %>
     
        <div>
            <%=Html.ActionLink("Back to List", "Index") %>
        </div>

    UserController.cs:

    public class UserController : Controller
        {
            public ActionResult Index()
            {
                IEnumerable<User> users =
                    UserRepository.GetAll();
     
                UserDisplay[] viewModel = users.Select(
                    user => new UserDisplay
                                {
                                    Username = user.Username,
                                    Name =
                                        user.FirstName + " " +
                                        user.LastName
                                }).ToArray();
     
                return View(viewModel);
            }
     
            [HttpGet]
            public ActionResult Display(int Id)
            {
                User user = UserRepository.GetById(Id);
     
                var viewModel = new UserDisplay
                                    {
                                        Username = user.Username,
                                        Name =
                                            user.FirstName + " " +
                                            user.LastName
                                    };
                return View(viewModel);
            }
     
            [HttpGet]
            public ActionResult Edit(int Id)
            {
                User users = UserRepository.GetById(Id);
     
                var viewModel = new UserInput
                                    {
                                        Username =
                                            users.Username,
                                        FirstName =
                                            users.FirstName,
                                        LastName =
                                            users.LastName,
                                    };
                return View(viewModel);
            }
     
     
            [HttpPost]
            public ActionResult Edit(UserInput input)
            {
                if (ModelState.IsValid)
                {
                    UpdateUserFromInput(input);
                    TempData["message"] = "The user was updated";
                    return RedirectToAction("index");
                }
     
                return View(input);
            }
     
            private void UpdateUserFromInput(UserInput input)
            {
                User user =
                    UserRepository.GetByUsername(input.Username);
                user.FirstName = input.FirstName;
                user.LastName = input.LastName;
                UserRepository.Save(user);
            }
        }
     
        public class UserDisplay
        {
            public string Username { get; set; }
            public string Name { get; set; }
        }
     
        public class UserInput
        {
            [Required]
            public string Username { get; set; }
     
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
     
     
        public static class UserRepository
        {
            public static IEnumerable<User> GetAll()
            {
                return new[]
                           {
                               new User
                                   {
                                       Username = "FFlintstone",
                                       FirstName = "Fred",
                                       LastName = "Flintstone"
                                   },
                               new User
                                   {
                                       Username = "brubble",
                                       FirstName = "Barney",
                                       LastName = "Rubble"
                                   },
                               new User
                                   {
                                       Username = "bbrubble",
                                       FirstName = "Bamm-Bamm",
                                       LastName = "Rubble"
                                   },
                               new User
                                   {
                                       Username = "wilma",
                                       FirstName = "Wilma",
                                       LastName = "Flintstone"
                                   },
                               new User
                                   {
                                       Username = "pebbles",
                                       FirstName = "Pebbles",
                                       LastName = "Flintstone"
                                   },
                               new User
                                   {
                                       Username = "dino",
                                       FirstName = "Dino",
                                       LastName = "Flintstone"
                                   },
                           };
            }
     
            public static User GetById(int id)
            {
                if (id == 2)
                    return new User();
                return new User
                           {
                               Username = "FFlintstone",
                               FirstName = "Fred",
                               LastName = "Flintstone"
                           };
            }
     
            public static User GetByUsername(string username)
            {
                return
                    GetAll().Where(s => s.Username == username).
                        FirstOrDefault();
            }
     
            public static void Save(User user)
            {
                
            }
        }
     
        public class User
        {
            public string Username { get; set; }
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }
     
     
     
     
     
     
     

    ASP.NET MVC2 in Action 读书笔记 [9-1] ChildAction

    1). ChildAction

    HomeController.cs:

    [HandleError]
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                ViewData["Message"] = "Welcome to ASP.NET MVC!";
     
                return View();
            }
     
            [ChildActionOnly]
            public ActionResult ChildAction()
            {
                return View();
            }
        }

    Index.aspx:

    <h2><%= Html.Encode(ViewData["Message"]) %></h2>
        <p>
            To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
        </p>
        <%Html.RenderAction("ChildAction"); %>

    ChildAction.aspx:

    <%@ Page Title="" Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
     
    <h2>This view was rendered by calling RenderAction. This is a ChildAction</h2>
     
     
     

    ASP.NET MVC2 in Action 读书笔记 [9-2] CustomActionResults

    Export.aspx:

    <h2>Export</h2>
        <a href="<%=Url.Action("ExportUsers") %>">Export Users as CSV</a>

    HomeController.cs:

    [HandleError]
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
                return View();
            }
     
            public ActionResult Export()
            {
                return View();
            }
     
            public ActionResult ExportUsers()
            {
                IEnumerable<User> model = UserRepository.GetUsers();
                return new CsvActionResult(model);
            }
     
            public ActionResult Logout()
            {
                return new LogoutActionResult(RedirectToAction("Index","Home"));
            }
        }

    CsvActionResult.cs:

    public class CsvActionResult : ActionResult 
        {
            public IEnumerable ModelListing { get; set; }
     
            public CsvActionResult(IEnumerable modelListing)
            {
                ModelListing = modelListing;
            }
     
            public override void ExecuteResult(ControllerContext context) 
            {
                byte[] data = new CsvFileCreator().AsBytes(ModelListing);
                
                var fileResult = new FileContentResult(data, "text/csv") 
                {
                    FileDownloadName = "CsvFile.csv"
                };
     
                fileResult.ExecuteResult(context);
            }
        }

    CsvFileCreator.cs:

    public class CsvFileCreator
        {
            public byte[] AsBytes(IEnumerable modelList)
            {
                StringBuilder sb = new StringBuilder();
                BuildHeaders(modelList, sb);
                BuildRows(modelList, sb);
                return sb.AsBytes();
            }
     
            private void BuildRows(IEnumerable modelList, StringBuilder sb)
            {
                foreach (object modelItem in modelList)
                {
                    BuildRowData(modelList, modelItem, sb);
                    sb.NewLine();
                }
            }
     
            private void BuildRowData(IEnumerable modelList, object modelItem, StringBuilder sb)
            {
                foreach (PropertyInfo info in modelList.GetType().GetElementType().GetProperties())
                {
                    object value = info.GetValue(modelItem, new object[0]);
                    sb.AppendFormat("{0},", value);
                }
            }
     
            private void BuildHeaders(IEnumerable modelList, StringBuilder sb)
            {
                foreach (PropertyInfo property in modelList.GetType().GetElementType().GetProperties())
                {
                    sb.AppendFormat("{0},",property.Name);                
                }
                sb.NewLine();
            }
        }

    StringBuilderExtensions.cs:

    public static class StringBuilderExtensions
        {
            public static void NewLine(this StringBuilder stringBuilder)
            {
                stringBuilder.Remove(stringBuilder.Length - 1, 1);
                stringBuilder.Append(Environment.NewLine);            
            }
            public static byte[] AsBytes(this StringBuilder stringBuilder)
            {
                return stringBuilder.ToString().Select(c => Convert.ToByte((char) c)).ToArray();            
            }
        }

    UserRepository.cs:

    public static class UserRepository
        {
            public static IEnumerable<User> GetUsers()
            {
                return new[]
                           {
                               new User
                                   {
                                       FirstName = "Fred",
                                       LastName = "Flintstone",
                                       LastLogin = new DateTime(2010, 3, 22),
                                       Username = "FFlintstone"
                                   },
                               new User
                                   {
                                       FirstName = "Willma",
                                       LastName = "Flintstone",
                                       LastLogin = new DateTime(2010, 1, 1),
                                       Username = "WFlintstone"
                                   },
                               new User
                                   {
                                       FirstName = "Jack",
                                       LastName = "Flintstone",
                                       LastLogin = new DateTime(2010, 2, 2),
                                       Username = "JFlintstone"
                                   },
                               new User
                                   {
                                       FirstName = "Jane",
                                       LastName = "Flintstone",
                                       LastLogin = new DateTime(2010, 3, 3),
                                       Username = "JaFlintstone"
                                   },
                           };
            }
        }

    User.cs:

    public class User
        {
            public string FirstName { get; set; }
            public string LastName { get; set; }
            public string Username { get; set; }
            public DateTime LastLogin { get; set; }
        }

    LogoutActionResult.cs:

    public class LogoutActionResult : ActionResult
        {
            public RedirectToRouteResult ActionAfterLogout { get; set; }
     
            public LogoutActionResult(RedirectToRouteResult actionAfterLogout)
            {
                ActionAfterLogout = actionAfterLogout;
            }
     
            public override void ExecuteResult(ControllerContext context)
            {
                FormsAuthentication.SignOut();
                ActionAfterLogout.ExecuteResult(context);
            }
        }
     

    ASP.NET MVC2 in Action 读书笔记 [12-1] Custom Ajax

    <script type="text/javascript">
            function getXmlHttpRequest() {
                var xhr;
                //check for IE implementation(s)
                if (typeof ActiveXObject != 'undefined') {
                    try {
                        xhr = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (e) {
                        xhr = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                } else if (XMLHttpRequest) {
                    //this works for Firefox, Safari, Opera    
                    xhr = new XMLHttpRequest();
                } else {
                    alert("Sorry, your browser doesn't support ajax");
                }
    
                return xhr;
            }
        
            function getMessage() {
                //get our xml http request object
                var xhr = getXmlHttpRequest();
    
                //prepare the request
                xhr.open("GET", "get_message.html", true)
                
                //setup the callback function
                xhr.onreadystatechange = function() {
                    //readyState 4 means we're done
                    if(xhr.readyState != 4) return;
                        
                    //populate the page with the result
                    document.getElementById('result').innerHTML = xhr.responseText;
                };
            
                //fire our request
                xhr.send(null);
            }
        </script>
    
    <button type="button" onclick="getMessage()">Get the Message</button>
    <div id="result"></div>
     
     

    ASP.NET MVC2 in Action 读书笔记 [12-2] Ajax with MVC

    Index.aspx:

    <script src="http://www.cnblogs.com/Scripts/jquery-1.3.2.js" type="text/javascript"></script>
        
        <script type="text/javascript">
            function getMessage() {
                $.get("/SimpleAjax/GetMessage", function(data) {
                    $("#result").html(data);
                });
            }
        </script>
     
    <button type="button" onclick="getMessage();">Get the Message!</button>
    <div id="result"></div>

     

    SimpleAjaxController.cs:

    public class SimpleAjaxController : Controller
        {   
            public ActionResult Index()
            {
                return View();
            }
     
            public ActionResult GetMessage()
            {
                return Content("<h1>This is a custom message returned from an action.</h1>");
            }
        }
     

    ASP.NET MVC2 in Action 读书笔记 [12-4] MVC Ajax Helpers

    Index.aspx:

    <script src="http://www.cnblogs.com/Scripts/jquery-1.3.2.js" type="text/javascript"></script>
        <script src="http://www.cnblogs.com/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
     
        <script src="http://www.cnblogs.com/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
     
     
    <h3>Ajax.BeginForm</h3>
        
        <h4>Comments</h4>    
        <ul id="comments">        
        </ul>
        
        <% using(Ajax.BeginForm("AddComment", new AjaxOptions
                                                {
                                                    HttpMethod = "POST", 
                                                    UpdateTargetId = "comments",
                                                    InsertionMode = InsertionMode.InsertAfter                                                
                                                })) { %>
        
            <%= Html.TextArea("Comment", new{rows=5, cols=50}) %>
            <button type="submit">Add Comment</button>
                                                
        <% } %>
        
        <h3>Ajax.Link</h3>
        
        <%= Ajax.ActionLink("Show the privacy Policy", "PrivacyPolicy", 
            new AjaxOptions{InsertionMode = InsertionMode.Replace, UpdateTargetId = "privacy"}) %>
     
        <div id="privacy"></div>

     

    AjaxHelpersController.cs:

    public class AjaxHelpersController : Controller
        {
            private IList<string> _comments = new List<string>();
     
            public ActionResult Index()
            {
                return View(_comments);
            }
     
            [HttpPost]
            public ActionResult AddComment(string comment)
            {
                _comments.Add("<li>" + comment + "</li>");
                return Content(string.Join("\n", _comments.ToArray()));
            }
     
            public ActionResult PrivacyPolicy()
            {
                const string privacyText = @"
                    <h2>Our Commitment To Privacy</h2>
                    Your privacy is important to us. To better protect your privacy we provide this notice explaining our online 
                    information practices and the choices you can make about the way your information is collected and used. 
                    To make this notice easy to find, we make it available on our homepage and at every point where personally 
                    identifiable information may be requested.";
     
                return Content(privacyText, "text/html");
            }
        }
     
     

    MVC2 强类型的 HTML Helper

    在 MVC2 之后,开始支持一系列强类型的方式来生成 HTML. 这些方法的名字形式为 Html.HelperNameFor() , 例如,Html.TextBoxFor(), Html.CheckBoxFor() 等等。

    例如,使用下面的形式:

    需要注意的是,这是一个 Lambda 表达式,所以,我们并不需要写出 ProductName 来。在 VS 中,通过强类型的 Model,当使用 Lambda 表达式的时候,Visual Studio 可以给出提示。

    生成的 HTML 如下所示:

    在 ASP.NET MVC2 中支持的方式如下:

    HTML 元素的助手

    • Html.TextBoxFor()
    • Html.TextAreaFor()
    • Html.DropDownListFor()
    • Html.CheckboxFor()
    • Html.RadioButtonFor()
    • Html.ListBoxFor()
    • Html.PasswordFor()
    • Html.HiddenFor()
    • Html.LabelFor()

    还有其它的助手

    • Html.EditorFor()
    • Html.DisplayFor()
    • Html.DisplayTextFor()
    • Html.ValidationMessageFor()

    ASP.NET MVC 音乐商店 - 目录

    posted @ 2011-11-23 22:50 冠军 阅读(2392) | 评论 (6) 编辑

    ASP.NET MVC 音乐商店 - 10. 完成导航和站点的设计

    posted @ 2011-11-21 19:32 冠军 阅读(1675) | 评论 (8) 编辑

    ASP.NET MVC 音乐商店 - 9. 注册和结账

    posted @ 2011-11-20 23:24 冠军 阅读(1555) | 评论 (3) 编辑

    ASP.NET MVC 音乐商店 - 8. 使用 Ajax 更新的购物车

    posted @ 2011-11-20 00:10 冠军 阅读(1366) | 评论 (8) 编辑

    ASP.NET MVC 音乐商店 - 7.成员管理和授权

    posted @ 2011-11-18 04:09 冠军 阅读(1812) | 评论 (5) 编辑

    ASP.NET MVC 音乐商店 - 6. 使用 DataAnnotations 进行模型验证

    posted @ 2011-11-16 22:44 冠军 阅读(1410) | 评论 (3) 编辑

    ASP.NET MVC 音乐商店 - 5 通过支架创建编辑表单 续

    posted @ 2011-11-15 20:18 冠军 阅读(1722) | 评论 (7) 编辑

    ASP.NET MVC 音乐商店 - 5. 通过支架创建编辑表单

    posted @ 2011-11-15 03:30 冠军 阅读(2050) | 评论 (11) 编辑

    ASP.NET MVC 音乐商店 - 4. 数据访问

    posted @ 2011-11-13 22:43 冠军 阅读(2598) | 评论 (22) 编辑

    ASP.NET MVC 音乐商店 - 3. 视图与模型

    posted @ 2011-11-11 19:25 冠军 阅读(2189) | 评论 (11) 编辑

    ASP.NET MVC 音乐商店 - 2.控制器

    posted @ 2011-11-10 19:47 冠军 阅读(2150) | 评论 (7) 编辑

    ASP.NET MVC 音乐商店 - 1 创建项目

    posted @ 2011-11-09 20:42 冠军 阅读(2285) | 评论 (13) 编辑

    ASP.NET MVC 音乐商店 - 0 概览

    posted @ 2011-11-08 21:46 冠军 阅读(2946) | 评论 (21) 编辑

    MVC View 中 html 属性名与关键字冲突问题的分析与解决

    posted @ 2011-09-07 12:20 冠军 阅读(387) | 评论 (5) 编辑

    ASP.NET MVC 模型绑定的 6 个建议

    posted @ 2011-08-01 18:57 冠军 阅读(885) | 评论 (4) 编辑

    测试 MVC 之 Mock HttpContext

    posted @ 2011-07-24 20:21 冠军 阅读(1243) | 评论 (5) 编辑

    MVC2 强类型的 HTML Helper

    posted @ 2011-05-13 11:35 冠军 阅读(576) | 评论 (0) 编辑

    EF Code First 和 ASP.NET MVC3 工具更新

    posted @ 2011-05-06 22:59 冠军 阅读(3522) | 评论 (15) 编辑

    NuGet Action Plan - 更新到 1.1, 设置自动更新,获取 NuGet 包浏览器

    posted @ 2011-04-26 16:00 冠军 阅读(1169) | 评论 (4) 编辑

    使用 zip 压缩包手动安装 Orchard

    posted @ 2011-04-22 22:09 冠军 阅读(1141) | 评论 (0) 编辑

    翻译:使用 Entity Framework 4.x 进行代码优先 (Code-First) 开发

    posted @ 2011-04-03 13:13 冠军 阅读(2372) | 评论 (11) 编辑

    ASP.NET MVC3 Service Location

    posted @ 2011-01-22 17:56 冠军 阅读(2007) | 评论 (5) 编辑

    在没有安装 ASP.NET MVC3 的服务器上运行 MVC3

    posted @ 2011-01-20 00:43 冠军 阅读(4250) | 评论 (15) 编辑

    ASP.NET MVC 3 概述

    posted @ 2011-01-15 22:17 冠军 阅读(6936) | 评论 (10) 编辑

    ASP.NET MVC3 及其学习资源

     

    MVC3中输出Html标签的方法

     

    @{string a="<a>111</a>";}

    想要输出html,可以三种方式:
    @Html.Raw(a)
    @MvcHtmlString.Create(a)
    @{WriteLiteral(a);}

     

    @(new HtmlString( "<h1>asdfasd</h1>")) 
    @(Html.Encode("<h1>asdfasd</h1>"))

     

     

    ASP.NET MVC 超简单 分页

     

     

    mvc1,mvc2,mvc3都有什么区别

     

    ----------------------------------------

    public ActionResult Details(int id)
        using (var context = new DbEntities())
        {             
            var entity = context.Entities.
              Include(e => e.OtherEntities).
              FirstOrDefault(e => e.EntityId == id);
            return Json(entity, JsonRequestBehavior.AllowGet);
        }
    }

     

    Pay attention that this is a fake method and isn’t a real method.

    The error I was getting didn’t show up on the server side (nothing crashed). I found the error by inspectingFiddler since the application kept on working but the client side callback wasn’t. Here is an example of the calling client side function which is using jQuery getJSON function:

     

    function getDetails() {
        $.getJSON('/ApplicationName/Details/' + Id, {}, function (data) {
            fillDetails(data);
        });
    }

     

    -------------------------------------------

     

    扩展ASP.NET MVC HtmlHelper类

     

    这篇帖子中我会使用一个示例演示扩展ASP.NET MVC HtmlHelper类,让它们可以在你的MVC视图中工作。这个示例中我会提供一个简单的方案生成Html表格。

    HtmlHelper类

    HtmlHelper类用于在ASP.NET MVC framework中帮助视图呈现html部分。

    这个类提供了一些方法,你可以使用这些方法呈现html中的一些类型(textbox,checkbox等),或者html的一部分(如form)。ASP.NET MVC framework helper有这些内容:

    • Html.ActionLink()

    • Html.BeginForm()

    • Html.CheckBox()

    • Html.DropDownList()

    • Html.EndForm()

    • Html.Hidden()

    • Html.ListBox()

    • Html.Password()

    • Html.RadioButton()

    • Html.TextArea()

    • Html.TextBox()

    比如说你要显示一个用name属性为myChkbox并且已经勾选的复选框,可以这样写:

    <%=Html.CheckBox(“myChkbox”, true) %>

    所有的html helper都是由扩展方法创建的,设在System.Web.Mvc.Html名称空间。

    为HtmlHelper创建Html表格扩展

    在本示例中我写了一个扩展方法,用于支持html表格的呈现。你可以修改它或者创建你自己的示例。

     

    public static class MVCHelpers
    {
        
    public static string Table(this HtmlHelper helper, string name, IList items, IDictionary<stringobject> attributes)
        {
            
    if (items == null || items.Count == 0 || string.IsNullOrEmpty(name))
            {                
                
    return string.Empty;
            }

            
    return BuildTable(name, items, attributes);            
        }

        
    private static string BuildTable(string name, IList items, IDictionary<stringobject> attributes)
        {
            StringBuilder sb 
    = new StringBuilder();
            BuildTableHeader(sb, items[
    0].GetType());

            
    foreach (var item in items)
            {
                BuildTableRow(sb, item);
            }

            TagBuilder builder 
    = new TagBuilder("table");
            builder.MergeAttributes(attributes);
            builder.MergeAttribute(
    "name", name);
            builder.InnerHtml 
    = sb.ToString();            
            
    return builder.ToString(TagRenderMode.Normal);
        }

        
    private static void BuildTableRow(StringBuilder sb, object obj)
        {
            Type objType 
    = obj.GetType();
            sb.AppendLine(
    "\t<tr>");
            
    foreach (var property in objType.GetProperties())
            {
                sb.AppendFormat(
    "\t\t<td>{0}</td>\n", property.GetValue(obj, null));
            }
            sb.AppendLine(
    "\t</tr>");
        }

        
    private static void BuildTableHeader(StringBuilder sb, Type p)
        {
            sb.AppendLine(
    "\t<tr>");
            
    foreach (var property in p.GetProperties())
            {
                sb.AppendFormat(
    "\t\t<th>{0}</th>\n", property.Name);
            }
            sb.AppendLine(
    "\t</tr>");
        }
    }


     

    你可以看到我如何利用扩展方法Table扩展HtmlHelper类。BuildTable方法是主要方法,它利用ASP.NET MVC TagBuilder类来创建table标签。你可以看到在我的示例用,我使用了反射,获取各项的属性列表,并且把这些属性名称作为表头,它们的值填充为 表格单元格。

    在视图中使用Html.Table扩展方法

    如果你想使用这个自定义html helper,只需要做这些:

    • 在视图中用注册helper所在的名称空间:<%@ Import Namespace=”TaskList.Models” %>
    • 使用视图的Html属性中的Table方法,例如创建一个name属性为myTable,并使用视图中当前模型的例 子:<%=Html.Table(”myTable”, (IList)ViewData.Model, null) %>,注意Model如果不是IList,会出现异常。

     

    总结

    在这篇帖子中我介绍了HtmlHelper类,和如何为这个类创建一个简单的扩展方法。也可以通过创建你自己的类(如TableHelper)来扩展 HtmlHelper,你需要做的只是创建方法,并返回所要呈现的html。在我看来,使用扩展方法比较简单一点。

     

  • 相关阅读:
    第二章 搭建Android开发环境
    彻底修改 Windows 系统用户名
    第一章 Android系统移植与驱动开发概述
    返回一个整数数组中最大子数组的和。
    返回一个二维整数数组中最大子数组的和。
    返回一个整数数组中最大的子数组的和。
    四则运算
    关于南方Cass的使用感受
    数据结构-王道2017-第3章 栈和队列-栈和队列的应用
    数据结构-王道2017-第3章 栈和队列-队列
  • 原文地址:https://www.cnblogs.com/fx2008/p/2283796.html
Copyright © 2020-2023  润新知