I'm quite new to both ASP.Net and MVC.
I got the following code in my master page:
<div id="main-menu" class="menu">
<%
var items = (IList<CompanyName.Framework.Web.MenuItem>)ViewData["MainMenu"];
if (items.Count > 0)
{
%><ul><%
foreach (var item in items)
{
if (!string.IsNullOrEmpty(item.RequiredRole) && !System.Threading.Thread.CurrentPrincipal.IsInRole(item.RequiredRole))
continue;
%><li><%= item.Title %></li><%
}
%></ul><%
}
%>
</div>
Can I move the code to another file or refactor the code in any way?
edit:
My ApplicationController that all controllers derive:
public class ApplicationController : Controller
{
List<MenuItem> _mainMenu = new List<MenuItem>();
List<MenuItem> _contextMenu = new List<MenuItem>();
protected IList<MenuItem> MainMenu
{
get { return _mainMenu; }
}
protected IList<MenuItem> ContextMenu
{
get { return _contextMenu; }
}
protected string PageTitle { get; set; }
protected override void OnResultExecuting(ResultExecutingContext filterContext)
{
ViewData["PageTitle"] = PageTitle;
ViewData["MainMenu"] = MainMenu;
ViewData["ContextMenu"] = ContextMenu;
base.OnResultExecuting(filterContext);
}
}
Here are a couple of suggestions:
Improvement number 1: use view models and strongly typed views instead of ViewData
public ActionResult Index()
{
// TODO: Fetch this data from a repository
var menus = new[] {
new MenuItem(), new MenuItem()
}.ToList();
return View(menus);
}
and then in your view:
<div id="main-menu" class="menu">
<%
if (Model.Count > 0)
{
%><ul><%
foreach (var item in Model)
{
if (!string.IsNullOrEmpty(item.RequiredRole) && !System.Threading.Thread.CurrentPrincipal.IsInRole(item.RequiredRole))
continue;
%><li><%= item.Title %></li><%
}
%></ul><%
}
%>
</div>
Still horrible and completely unreadable tag soup.
Improvement number 2: use editor/display templates:
In ~/Views/Home/DisplayTemplates/MenuItem.ascx:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CompanyName.Framework.Web.MenuItem>" %>
<% if (!string.IsNullOrEmpty(Model.RequiredRole) &&
System.Threading.Thread.CurrentPrincipal.IsInRole(Model.RequiredRole)) { %>
<li>
<%= Model.Title %>
</li>
<% } %>
And then in your main view:
<div id="main-menu" class="menu">
<ul>
<%= Html.DisplayForModel() %>
</ul>
</div>
Improvement number 3: Avoid coding business rules in a view. So in your view model add a property:
public bool IsLinkVisible
{
get
{
return !string.IsNullOrEmpty(RequiredRole) &&
Thread.CurrentPrincipal.IsInRole(RequiredRole);
}
}
so that your display template now looks like this:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CompanyName.Framework.Web.MenuItem>" %>
<% if (Model.IsLinkVisible) { %>
<li>
<%= Model.Title %>
</li>
<% } %>
Improvement number 4: Write a custom HTML helper to render this anchor because writing C# in a view is still ugly and untestable:
public static class HtmlExtensions
{
public static MvcHtmlString MenuItem(this HtmlHelper<MenuItem> htmlHelper)
{
var menuItem = htmlHelper.ViewData.Model;
if (!menuItem.IsLinkVisible)
{
return MvcHtmlString.Empty;
}
var li = new TagBuilder("li");
var a = new TagBuilder("a");
a.MergeAttribute("href", menuItem.Uri);
a.SetInnerText(menuItem.Title);
li.InnerHtml = a.ToString();
return MvcHtmlString.Create(li.ToString());
}
}
and finally your display template:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CompanyName.Framework.Web.MenuItem>" %>
<%= Html.MenuItem() %>
Yes, you can just put that block into an .ascx file and use:
<% html.RenderPartial("myPartialFile.asx"); %>
The above assumes that myPartialFile.ascx is located in the same folder as your master page, usually, the Views/Shared folder.
Related
I am trying to convert the popular asp.net MVC 2.0 solr.net sample app code to Razor syntax. I am not able to understand the last line ... Kindly help
<% Html.Repeat(new[] { 5, 10, 20 }, ps => { %>
<% if (ps == Model.Search.PageSize) { %>
<span><%= ps%></span>
<% } else { %>
#ps
<% } %>
<% }, () => { %> | <% }); %>
[update]
Source for Html.Repeat extension
HtmlHelperRepeatExtensions.cs
For this to work you will have to modify the Html.Repeat extension method to take advantage of Templated Razor Delegates as illustrated by Phil Haack. And then:
#{Html.Repeat(
new[] { 5, 10, 20 },
#<text>
#if (item == Model.Search.PageSize)
{
<span>#item</span>
}
else
{
<a href="#Url.SetParameters(new { pagesize = item, page = 1 })">
#item
</a>
}
</text>,
#<text>|</text>
);}
UPDATE:
According to your updated question you seem to be using a custom HTML helper but as I stated in my answer you need to updated this helper to use the Templated Razor Delegates syntax if you want it to work. Here's for example how it might look:
public static class HtmlHelperRepeatExtensions
{
public static void Repeat<T>(
this HtmlHelper html,
IEnumerable<T> items,
Func<T, HelperResult> render,
Func<dynamic, HelperResult> separator
)
{
bool first = true;
foreach (var item in items)
{
if (first)
{
first = false;
}
else
{
separator(item).WriteTo(html.ViewContext.Writer);
}
render(item).WriteTo(html.ViewContext.Writer);
}
}
}
or if you want to have the helper method directly return a HelperResult so that you don't need to use the brackets when calling it:
public static class HtmlHelperRepeatExtensions
{
public static HelperResult Repeat<T>(
this HtmlHelper html,
IEnumerable<T> items,
Func<T, HelperResult> render,
Func<dynamic, HelperResult> separator
)
{
return new HelperResult(writer =>
{
bool first = true;
foreach (var item in items)
{
if (first)
first = false;
else
separator(item).WriteTo(writer);
render(item).WriteTo(writer);
}
});
}
}
and then inside your view:
#Html.Repeat(
new[] { 5, 10, 20 },
#<text>
#if (item == Model.Search.PageSize)
{
<span>#item</span>
}
else
{
<a href="#Url.SetParameters(new { pagesize = item, page = 1 })">
#item
</a>
}
</text>,
#<text>|</text>
)
Possibly something like:
}, () => { <text>|</text> });
I want to display all the images in my image's folder.
This is my code :
<%
string dir = Server.MapPath("Content/slideshow/images");
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dir);
numFiles = files.Length;
for (int i = 1; i < numFiles; i++)
{
%>
<i><a href="#">
<img src="/Content/slideshow/images/image<%= i %>.jpg" alt="" height="239px" width="930px" />
</a></i>
<% }%>
When I code like this, it display only the images that have the name "image"+blah blah blah . But I want to render all images in different name in a folder.
Can anyone solve this?
I would suggest you using view models to achieve this. So let's start by defining such:
public class ImageViewModel
{
public string Url { get; set; }
}
then we could have a controller action which will populate this view model (or precisely a collection of it):
public class ImagesController: Controller
{
[ChildActionOnly]
public ActionResult Images()
{
var appData = Server.MapPath("~/Content/slideshow/images");
var images = Directory.GetFiles(appData).Select(x => new ImageViewModel
{
Url = Url.Content("~/Content/slideshow/images/" + Path.GetFileName(x))
});
return PartialView(images);
}
}
then we could define a corresponding partial view (~/Views/Shared/Images.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<ImageViewModel>>"
%>
<%= Html.DisplayForModel() %>
next a corresponding display template which will be rendered for each image (~/Views/Shared/DisplayTemplates/ImageViewModel.ascx):
<%# Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<ImageViewModel>"
%>
<img src="<%= Model.Url %>" alt="" height="239px" width="930px" />
and the final part that's left is to include this child action somewhere in a view or a master page:
<%= Html.Action("Images", "Images") %>
public DisplayImages()
{
System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(Location);
foreach (System.IO.FileInfo f in dir.GetFiles("*.*"))
{
//Do Something
}
}
I'm experiencing current error in my view:
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ProjectenII.Models.Domain.StudentModel>"%>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
IndexStudents
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>IndexStudents</h2>
<%using (Html.BeginForm()) { %>
<%=Html.ListBoxFor(model => model.NormalSelected, new MultiSelectList(Model.NormalStudentsList, "StudentNummer", "Naam", Model.NormalSelected), new { size = "6" }); %>
<input type="submit" name="add"
id="add" value=">>" /><br />
<input type="submit" name="remove"
id="remove" value="<<" />
<%=Html.ListBoxFor(model => model.NoClassSelected, new MultiSelectList(Model.StudentsNoClassList, "StudentNummer", "Naam", Model.NoClassSelected)); %>
<% } %>
<%=Html.HiddenFor(model => model.Save) %>
<input type="submit" name="apply" id="apply" value="Save!" />
</asp:Content>
It gives me an error at the listboxfor() method... saying ") expected".
But I close all the opening tags... very strange though!
What I want to use it for: I want to move items from one listbox to the other and then update the database. So I'd like to do it using formCollection, unless there is another way?
Students have a field named "classID", when I update the database, that value needs to change from the current value to "0". I think the best way is using formCollections? Isn't it?
This is my StudentModel
public class StudentModel
{
public IEnumerable<Student> NormalStudentsList { get; set; }
public IEnumerable<Student> StudentsNoClassList { get; set; }
public string[] NormalSelected { get; set; }
public string[] NoClassSelected { get; set; }
public string Save { get; set; }
}
Controller:
public ActionResult IndexStudents(Docent docent, int id, int klasgroepid)
{
var studentModel = new StudentModel
{
NormalStudentsList = docent.GeefStudenten(id, klasgroepid),
StudentsNoClassList = docent.GeefStudenten(id, klasgroepid)
};
return View(studentModel);
}
I have two questions: how can I fix the error? AND how can I update the database?
I suggest using "UpdateModel()" ... ?
Thanks in advance!!
Not sure what your second question is because you didn't include the code you're using to persist your model to the database.
The ")" expected error is because you have a semicolon at the end of your ListBoxFor method call.
It should look like this:
<%=Html.ListBoxFor(model => model.NormalSelected, new MultiSelectList(Model.NormalStudentsList, "StudentNummer", "Naam", Model.NormalSelected), new { size = "6" }) %>
When you use <%= you don't need the semicolon.
I have a timesheet application that has a View where the user can select customers and tasks and add them to a dynamic table. This table is filled with the tasks and input fields for filling in hours worked.
For adding the new tasks in the dynamic table I use jQuery, so the savenewtask button is not a submit button. Instead I have a proper submit button for saving the hours when filled in.
The View is strongly typed to a model called TimesheetViewModel (see below). The controller passes the model to the View, and then the input fields are bound to properties in the model.
However, when I submit with the submit button and try to update the model in the Controller it doesn't update. It seemed from the Nerddinner tutorial (which I am using to learn MVC) that the model should automatically be updated using the values from the forms fields it had been bound to when you use UpdateModel(). But it doesn't. What am I doing wrong?
Here is all the relevant code:
View:
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
//Hook onto the MakeID list's onchange event
$("#CustomerId").change(function () {
//build the request url
var url = "Timesheet/CustomerTasks";
//fire off the request, passing it the id which is the MakeID's selected item value
$.getJSON(url, { id: $("#CustomerId").val() }, function (data) {
//Clear the Model list
$("#TaskId").empty();
//Foreach Model in the list, add a model option from the data returned
$.each(data, function (index, optionData) {
$("#TaskId").append("<option value='" + optionData.Id + "'>" + optionData.Name + "</option>");
});
});
}).change();
});
</script>
<h2>Index</h2>
<% using (Html.BeginForm())
{%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<legend>Fields</legend>
<div>
<label for="Customers">
Kund:</label>
<%:Html.DropDownListFor(m => m.Customers, new SelectList(Model.Customers, "Id", "Name"), "Välj kund...", new { #id = "CustomerId" })%>
<label for="Tasks">
Aktiviteter:</label>
<select id="TaskId">
</select>
</div>
<p>
<input type="button" value="Save new task" id="savenewtask" />
</p>
<table width="100%">
<%--<% foreach (var task in Model.Tasks)--%>
<% foreach (var task in Model.WeekTasks)
{ %>
<tr>
<td>
<%: task.Customer.Name %>
</td>
<td>
<%: task.Name %>
</td>
<td>
<% foreach (var ts in task.TimeSegments)
{ %>
<input class="hourInput" type="text" size="2" id="<%: ts.Task.CustomerId + '_' + ts.TaskId + '_' + ts.Date %>"
value="<%: ts.Hours %>" />
<% } %>
</td>
</tr>
<% } %>
</table>
<input type="submit" value="Save hours" id="savehours" />
</fieldset>
<% } %>
</asp:Content>
From the Controller:
private TimesheetViewModel _model;
public TimesheetController()
{
_model = new TimesheetViewModel();
}
public ActionResult Index()
{
return View(_model);
}
[HttpPost]
public ActionResult Index(FormCollection collection)
{
try
{
UpdateModel(_model);
_model.Save();
return View(_model);
//return RedirectToAction("Index");
}
catch
{
return View();
}
}
The ViewModel:
public class TimesheetViewModel
{
private TimesheetContainer _model; //TimesheeContainer is an Entity Framework model
public TimesheetViewModel()
{
_model = new TimesheetContainer();
}
public IList<Customer> Customers
{ get { return _model.Customers.ToList(); } }
public IList<Task> Tasks
{ get { return _model.Tasks.ToList(); } }
public IList<Task> WeekTasks
{
get
{
//Get the time segments for the current week
DateTime firstDayOfWeek = DateTime.Parse("2010-12-05");
DateTime lastDayOfWeek = DateTime.Parse("2010-12-13");
List<TimeSegment> timeSegments = new List<TimeSegment>();
foreach (var timeSegment in _model.TimeSegments)
{
if(timeSegment.DateTimeDate > firstDayOfWeek && timeSegment.DateTimeDate < lastDayOfWeek)
timeSegments.Add(timeSegment);
}
//Group into tasks
var tasks = from timeSegment in timeSegments
group timeSegment by timeSegment.Task
into t
select new { Task = t.Key };
return tasks.Select(t => t.Task).ToList();
}
}
public IList<TimeSegment> TimeSegments
{ get { return _model.TimeSegments.ToList(); } }
public void Save()
{
_model.SaveChanges();
}
public void AddTimeSegments(Task task)
{
_model.AddToTasks(task);
_model.SaveChanges();
}
}
Partial class to get tasks for a specific week (only dummy week at this time for testing):
public partial class TimeSegment
{
public DateTime DateTimeDate
{ get { return DateTime.Parse(Date); } }
}
Why is the model not updating, and what can I change to make it work?
Put a breakpoint on your first ActionResult Index(), is that getting called when you do the submit? you may need [HttpGet] on it, otherwise I think it gets both.
Ok, I've been going at this for several hours and I simply cannot find the solution.
I want to get some data from my user. So first, I use a controller to create a view which receives a Model:
public ViewResult CreateArticle()
{
Article newArticle = new Article();
ImagesUploadModel dataFromUser = new ImagesUploadModel(newArticle);
return View(dataFromUser);
}
Then, I have the view:
<asp:Content ID="Content1" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<h2>AddArticle</h2>
<% using (Html.BeginForm("CreateArticle", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" })){ %>
<%= Html.LabelFor(model => model.newArticle.Title)%>
<%= Html.TextBoxFor(model => model.newArticle.Title)%>
<%= Html.LabelFor(model => model.newArticle.ContentText)%>
<%= Html.TextBoxFor(model => model.newArticle.ContentText)%>
<%= Html.LabelFor(model => model.newArticle.CategoryID)%>
<%= Html.TextBoxFor(model => model.newArticle.CategoryID)%>
<p>
Image1: <input type="file" name="file1" id="file1" />
</p>
<p>
Image2: <input type="file" name="file2" id="file2" />
</p>
<div>
<button type="submit" />Create
</div>
<%} %>
</asp:Content>
and finally - the original controller, but this time configured to accept the data:
[HttpPost]
public ActionResult CreateArticle(ImagesUploadModel dataFromUser)
{
if (ModelState.IsValid)
{
HttpPostedFileBase[] imagesArr;
imagesArr = new HttpPostedFileBase[2];
int i = 0;
foreach (string f in Request.Files)
{
HttpPostedFileBase file = Request.Files[f];
if (file.ContentLength > 0)
imagesArr[i] = file;
}
The rest of this controller does not matter since no matter what I do, the count attribute of Request.Files (or Request.Files.Keys) remains 0. I simply can't find a way to pass the files from the form (the Model passes just fine).
You might want to consider not posting the files with the rest of the form- there are good reasons and other ways you can achieve what you want.
Also, check out this question and this advice regarding file uploads in MVC.
You could add the files to your view model:
public class ImagesUploadModel
{
...
public HttpPostedFileBase File1 { get; set; }
public HttpPostedFileBase File2 { get; set; }
}
And then:
[HttpPost]
public ActionResult CreateArticle(ImagesUploadModel dataFromUser)
{
if (ModelState.IsValid)
{
// Use dataFromUser.File1 and dataFromUser.File2 directly here
}
return RedirectToAction("index");
}