Skip to content

Instantly share code, notes, and snippets.

@ilovejs
Created June 23, 2014 13:49
Show Gist options
  • Save ilovejs/1d7e06c05c567ac917c1 to your computer and use it in GitHub Desktop.
Save ilovejs/1d7e06c05c567ac917c1 to your computer and use it in GitHub Desktop.
Notes for asp.net mvc 4 in action
//Server side
public ViewResult Show(int id)
{
var entry = _db.Entries.Find(id);
bool hasPermission = User.Identity.Name == entry.Name;
ViewData["hasPermission"] = hasPermission;
return View(entry);
}
//View
<p>
@{
bool hasPermission =
(bool) ViewData["hasPermission"];
}
@if (hasPermission)
{
@Html.ActionLink("Edit", "Edit",
new {id = Model.Id})
}
@Html.ActionLink("Back to Entries", "Index")
</p>
ViewData Dictionary syntactically it isn’t very nice to work with—you have to perform type casts
whenever you want to retrieve something from the dictionary.
ViewBag approach:
//Controller
ViewBag.HasPermission = hasPermission;
//View
<p>
@if (ViewBag.HasPermission)
{
@Html.ActionLink("Edit", "Edit", new {id = Model.Id})
}
@Html.ActionLink("Back to Entries", "Index")
</p>
The generic WebViewPage<T> inherits from WebViewPage but offers some unique additions not avail-
able in the nongeneric WebViewPage class.
public class WebViewPage<TModel> : WebViewPage
{
public new AjaxHelper<TModel> Ajax { get; set; }
public new HtmlHelper<TModel> Html { get; set; }
public new TModel Model { get; }
public new ViewDataDictionary<TModel> ViewData { get; set; }
}
See ? There are some strongly typed object.
//List inside controller
public ActionResult Index()
{
var mostRecentEntries = (from entry in _db.Entries
orderby entry.DateAdded descending
select entry).Take(20);
var model = mostRecentEntries.ToList();
return View(model);
}
//List object in view
@using Guestbook.Models
@model List<GuestbookEntry>
//
public class LogOnModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "Remember me?")]
public bool RememberMe { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment