I have some tabs in bootstrap which has to be set as active depending on the action being hit. I have sub-tabs as well which has to be set as active depending on the action being hit as well.
Here is an image of how it looks like:
So when a sub-tab is being active the parent tab has to be active too.
So I thought to create a new Attribute where I save a pageId for each action and depending on the pageId on the view I can set it to active or not:
Here is the attribute:
public class YcoPageId : Attribute
{
public YcoPageId(int pageId)
{
PageId = pageId;
}
public int PageId { get; }
}
Here is the action:
[YcoPageId(1)]
public ActionResult Admin()
{
return View();
}
For the view I want to create an extension method to see if the tab and sub-tabs shall be active or not!
Here is my code:
public static bool IsActive(this HtmlHelper htmlHelper, params int[] ids)
{
var viewContext = htmlHelper.ViewContext;
var action = viewContext....
//How to get the YcoPageId attribute from here and see the Id
//Here i will test if ids contain id but dont know how to get it...
}
If you think adding an id for each page is bad idea I think for my case I will use this id for other purposes as well because it will be like identifier for a specific action...
So my question is how can I get the attribute YcoPageId for current action in my extension method ?
The view will look like this:
<li class="#(Html.IsActive(1, 4, 5... etc)? "active" : "")">
<a href="#url">
<div class="row text-center">
<div class="col-md-12">
<i class="fa #fontAwesomeIcon fa-4x" aria-hidden="true"></i>
<br/>#menuName
</div>
</div>
</a>
</li>
If there is any better idea how to solve this issue please go ahead!
Here is my solution to this problem:
First created a actionfilter attribute like below:
public class YcoPageIdAttribute : ActionFilterAttribute
{
public YcoPageIdAttribute(int pageId)
{
PageId = pageId;
}
public int PageId { get; }
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if (filterContext.Result is ViewResult)
{
filterContext.Controller.TempData[DomainKeys.ViewPageId] = PageId;
}
else
{
throw new Exception("Only ViewResult has unique id");
}
base.OnActionExecuted(filterContext);
}
}
Then my action would look like this one:
[YcoPageId(1)]
public ActionResult Admin()
{
return View();
}
I created an extension method like below:
public static bool IsActive(this HtmlHelper htmlHelper, params int[] ids)
{
var viewContext = htmlHelper.ViewContext;
return viewContext.TempData.ContainsKey(DomainKeys.ViewPageId) &&
int.Parse(viewContext.TempData.Peek(DomainKeys.ViewPageId).ToString()).In(ids);
}
Since I know the id of an action now I have only to put the code as below in the view:
<li class="#(Html.IsActive(1)? "active" : "")">
<a href="#url">
<div class="row text-center">
<div class="col-md-12">
<i class="fa #fontAwesomeIcon" aria-hidden="true"></i>
<br /><small>#menuName</small>
</div>
</div>
</a>
</li>
I made another method on startup to check if I have actions with duplicated values like below:
public static void CheckForDuplicateActionId()
{
Assembly asm = Assembly.GetExecutingAssembly();
var controllerActionlist = asm.GetTypes()
.Where(type => typeof(Controller).IsAssignableFrom(type))
.SelectMany(type => type.GetMethods(BindingFlags.Instance | BindingFlags.DeclaredOnly |
BindingFlags.Public))
.Where(m => !m.GetCustomAttributes(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute),
true).Any())
.Where(m => m.GetCustomAttribute<YcoPageIdAttribute>() != null)
.Select(
x =>
new
{
Controller = x.DeclaringType.Name,
Area = x.DeclaringType.FullName,
Action = x.Name,
ReturnType = x.ReturnType.Name,
Id = x.GetCustomAttribute<YcoPageIdAttribute>().PageId
})
.ToList();
var actionIds = controllerActionlist.Select(x => x.Id).ToList();
var actionIdsGrouped = actionIds.GroupBy(x => x).Where(x => x.Count() > 1).ToList();
if (!actionIdsGrouped.IsNullOrEmpty())
{
StringBuilder error = new StringBuilder("");
actionIdsGrouped.ForEach(actionId =>
{
var actions = controllerActionlist.Where(x => x.Id == actionId.Key);
actions.ForEach(a =>
{
error.Append(
$" | Id : {a.Id}, Action Name: {a.Action}, Controller Name : {a.Controller}, Location : {a.Area}. ");
});
});
var maxId = controllerActionlist.Max(x => x.Id);
error.Append(
"PLease consider changing the the duplicated id - Here are some options to choose from : Id {");
for (int i = 1, j = 1; i < maxId + 5; i++)
{
if (actionIds.Contains(i)) continue;
if (j < 5)
{
error.Append(i + ",");
j++;
}
else
{
error.Append(i + "}");
break;
}
}
throw new Exception(
$"There are more than one action duplicated with the same Id, The action data are as below : {error}");
}
}
Probably I will add all these data in database so I can identify an action from one id from database as well :)
Now it is working good.
If I understand correctly you are trying to create an id for each page/view and use it in the page/view to dynamically set css classes for setting menu tabs as active. If that is the case... Rather than trying to set the Ids in the Controller, how about creating a Shared View with only the following code - something like this....
In the View write the following Razor/C# code.
#{
var iPageId = 0
var sViewPath = ((System.Web.Mvc.BuildManagerCompiledView)ViewContext.View).ViewPath;
//for example
if (sViewPath.ToLower.IndexOf("admin") >= 0)
{
iPageId = 1;
}
else if (sViewPath.ToLower.IndexOf("dashboard") >= 0)
{
iPageId = 2;
}
else if (sViewPath.ToLower.IndexOf("vessels") >= 0)
{
iPageId = 3;
}
else if (sViewPath.ToLower.IndexOf("reports") >= 0)
{
iPageId = 4;
}
}
Render the Shared View in the primary view with the following snippet.
#Html.Partial("~/Views/Menu/_SharedViewName.cshtml")
Then you should be able to access the iPageId variable anywhere in the primary page/view(s) and set your CSS classes accordingly.
Related
Can somebody help me on the Lambda expression.
My ModelVM looks like :
namespace MReports.Models
{
public class FullDetailVM
{
public FullDetailVM()
{
DetailSet = new List<FullDetailSet>();
}
........
public List<FullDetailSet> DetailSet { get; set; }
}
public class FullDetailSet
{
public FullDetailSet(){ }
public string Mnum { get; set; }
public string Label { get; set; }
public string LabelValue { get; set; }
}
}
Data in the above model will be :
DetailSet[0] = {1,"MCity","LosAngeles"}
DetailSet[0] = {1,"MState","California"}
DetailSet[0] = {1,"MZip","90045"}
DetailSet[0] = {1,"MStreet","Cardiff"}
DetailSet[0] = {1,"MHouse No","1234"}
DetailSet[0] = {1,"MApt","1"}
View(Razor) :
#model MReports.Models.FullDetailVM
#if(Model != null)
{
<div class="row contentHeaderInfo">
<ul class="list-inline">
<li> City :
</li>
<li>
//Display LabelValue corresponding to Mcity
Model.DetailSet.select(LabelValue).Where(Label== "Mcity");
</li>
<li> State:
</li>
<li>
//Display LabelValue corresponding to MState
Model.DetailSet.select(LabelValue).Where(Label== "MState");
</li>
</ul>
</div>
}
Model.DetailSet.Where(x=>x.Label == "Mcity").Select(x=>x.LabelValue)
or if you have just one recors Label == Mcity
Model.DetailSet.SingleOrDefault(x=>x.Label == "Mcity").LabelValue
Lambda expressions can be used to create delegate types. I've found the easiest way to explain this to someone is to show them a list of items, such as your List<FullDetailSet> DetailSet, and ask them what items from that list do you want based on a specific condition?
If you wanted all the items with label "Dog" you would do something like this:
Model.DetailSet.Where(d => d.Label == "Dog").Select(d => d.Value);
This will go over the items in DetailSet and check if each item has a Label of "Dog". For lack of a better understanding on the correct terminology, you are iterating over that list and grabbing what you need based on your conditions. This is why I used d as the placeholder, to me it looks as though d is a singluar representation of DetailSet.
If you needed only one record from that DetailSet you would use Single over Where.
Model.DetailSet.Single(d => d.Label == "Dog").Select(d => d.Value);
If you didn't need just the Value of those records that met your conditions you can grab the entire list like this:
Model.DetailSet.Where(d => d.Label == "Dog").ToList();
You need to select one record using Single, then just get the property.
Model.DetailSet.Single(m => m.Label == "MState").LabelValue
I develop an application who manages formations of employees, I use MVC4 Asp.net with Razor.
In my model I have tow class (who are table in my database) formation and formateur (trainers).
In my application i can create a “formation” and I want to add a list of “formative”(trainers) but I don’t know what I must do.
I think the best solution it’s a list of checkbox, I succeeded to display my list of checkbox with a foreach but I have no idea how I get the result of selected checkbox to pass into my controller.
I saw many tutorials where use “CheckBoxList” and I tried to use too, but I use a ViewBag to populate it and they don't explain how to use it with a viewbag.
Now I test a Dual listBox with tow buttons (Add and Remove) but this doesn't work.
So, somebody can help me to find, and explain how I must do, the good or the best solution ?
I'm sorry for my english, I'm a french girl.
One of my solutions look like this :
My controller :
public ActionResult Create()
{
ViewBag.formateurListe = (from unFormateur in db.salarie
where unFormateur.sFormateur == true
select unFormateur).AsEnumerable()
.Select(m => new SelectListItem
{
Text = m.sNom.ToString() + " " + m.sPrenom.ToString(),
Value = m.sId.ToString()
}).ToList();
return View();
}
[HttpPost]
public ActionResult Create(formation formation, IEnumerable<SelectList> formateurList)
{
if (ModelState.IsValid)
{
db.formation.Add(formation);
foreach (var unSal in formateurList)
{
formateur f = new formateur();
f.ftIdFormation = formation.fId;
f.ftIdSalarie = (int)unSal.SelectedValue;
db.formateur.Add(f);
}
db.SaveChanges();
return RedirectToAction("Index");
}
return View(formation);
}
In my view :
#model MvcAppGestionRH.Models.formation
#using (Html.BeginForm("Create", "Formation", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
#Html.Label("Libelle")
#Html.EditorFor(model => model.fLibelle)
#Html.ValidationMessageFor(model => model.fLibelle)
<label id="fFormateur">Formateur</label>
#Html.ListBox("formateurListe", ViewData["formateurListe"] as SelectListItem[], new {Multiple = "multiple"})
<input type="button" value="+" name="add" />
<select name="select" size="7" >
</select>
<input type="submit" value="Créer" />
}
With a script :
$(function () {
$("#Add").click(function () {
$("select").add($('fFormateurListe').selected);
});
});
Checkboxes can be tricky the first time - I googled that a long time, too.
My solution is a view model which looks like this:
It is intended for questions, where the crator can speciy items via checkboxes (e.g. a questions might have the answer "GOOD" and "BAD".
public class QuestionModel
{
public int QuestionID { get; set; }
public string QuestionText { get; set; }
/// <summary>
/// Gets or sets the selected items. Purely a helper List to display check boxes for the user
/// </summary>
/// <value>
/// The selected items.
/// </value>
[Display(Name = "Items", ResourceType = typeof(Domain.Resources.Question))]
public IEnumerable<SelectListItem> SelectedItems { get; set; }
/// <summary>
/// Gets or sets the selected ids. Populated by the user, when he checks / unchecks items. Later translated into QuestionItems
/// </summary>
/// <value>
/// The selected ids.
/// </value>
public int[] SelectedIds { get; set; }
}
This is populated like this in the QuestionController:
private async Task GetSelectedItems(QuestionModel sm, Item selectedItems)
{
var alreadySelected = new List<Scale>();
if (selectedScale != null)
{
alreadySelected.Add(selectedScale);
}
var itemList = (await this.uoW.ItemRepository.Get()).OrderBy(i => i.Name);
sm.SelectedItems = itemList.Select(x => new SelectListItem
{
Value = x.ScaleID.ToString(),
Text = x.NameOfScale.GetText(),
Selected = (from a in alreadySelected where a.ItemID == x.ItemID select x).Any()
});
}
What does this do? It gets a list of all avialable items in the database and populates the model with it. Furthermore, you can pass in a list of items, which are already selected - so you can edit an existing question and siplay all already checked Items.
And n the view I have used a DropDownList:
<div class="form-group">
#Html.LabelFor(model => model.SelectedItems, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.DropDownListFor(x => x.SelectedIds, Model.SelectedItems, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SelectedItems, "", new { #class = "text-danger" })
</div>
</div>
</div>
If you want checkboxes, that looks like this(different controller, so dont be confused)
for (int i = 0; i < Model.SelectedItems.Count(); i++)
{
var currentElem = Model.SelectedItems[i];
//if this item is selected by the user, e.g. because he is editing the item, the item will be pre-selected
var selected = currentElem.Selected ? "checked=\"selected\"" : string.Empty;
// column for the questions. expected layout: list of all questions
<div class="col-md-6">
<div class="checkbox" id="SelectedIds">
<label>
<input type="checkbox" value="#currentElem.Value" #selected name="SelectedIds">
#Html.Encode(currentElem.Text)
</label>
</div>
</div>
}
and finally the create() method itself:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "QuestionText,SelectedItems, SelectedIds")] QuestionModel question)
{
if (ModelState.IsValid)
{
// I need only one Item, but if you want ore more change this line
if (question.SelectedIds.Count() == 1)
{
// better use Automapper here, this is unnecessary work
var newQuestion = new Question { QuestionText = question.QuestionText};
var ItemID = question.SelectedIds.First();
newQuestion.QuestionScale = await this.uoW.ItemRepository.GetRaw().Where(i => i.ItemID == ItemD).FirstAsync();
this.uoW.QuestionRepository.Insert(newQuestion);
await this.uoW.Save();
return this.RedirectToAction("Index");
}
else
{
this.logger.Warn("User {0} tried to insert more than one Itemin question {1}", User.Identity.Name, question.QuestionID);
ModelState.AddModelError(string.Empty, xyz.Areas.QuestionManagement.Resources.QuestionRes.ErrorTooManyScales);
}
}
else
{
// the SelectedItems are empty in the model - so if you have to redisplay it, repopulate it.
await this.GetSelectedItems(question, null);
}
return this.View(question);
}
Have you tried using a viewmodel to pass your two model in the view?
For example :
ViewModel
public class CreateFormationViewModel
{
public Formation formation{ get; set; }
public List<Formative> trainers {get;set;}
}
and then use this viewmodel in your view
An easy way to use this view model :
In your controller
public ActionResult CreateFormation()
{
//Get your data (formation and trainer)
CreateFormationViewModel createFormationVM = new CreateFormationViewModel();
createFormationVM.formation = YourFormationModel;
createFormationVM.trainers = YourtrainersModelasList;
//bind data to the view
return View(createFormationVM);
}
And in your View, you have :
#model [yournamespace].CreateFormationViewModel
While developing an ASP.Net MVC 4 application, I have followed the answer on pass enum to html.radiobuttonfor MVC3 and the answer from which it was derived, but my problem remains.
I am creating an edit page, and want to display Status as two radio buttons "Active" and "InActive", these values are read from the database as Enums 1 = Active , 2 = InActive.
The problem is, when the page is displayed it show's the correct radio button selected corresponding to the database value, but will not allow the user to change/select the other radio button ??
Any idea's, it's driving me nuts
(also changing the property to a bool for a chkbox will cause more problems than it will solve at this point. )
Controller.....
[HttpPost]
public ActionResult Edit(NewsArticle newsArticle, int id, HttpPostedFileBase Article)
{
try
{
if (ModelState.IsValid)
{
NewsArticle savedArticle= _newsArticle.Get(id);
savedArticle.Body = newsArticle.Body;
savedArticle.Title = newsArticle.Title;
savedArticle.Status = newsArticle.Status;
if(Article == null)
{
newsArticle.ArticleImage = savedArticle.ArticleImage;
}
else
{
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
newsArticle.ArticleImage = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
savedArticle.ArticleImage = newsArticle.ArticleImage;
string imgeName = Path.GetFileName(Article.FileName);
savedArticle.ImageName = imgeName;
}
_uow.SaveChanges();
return RedirectToAction("Index");
}
View..........
<div class="control-group">
<div class="editor-field">
<label class="control-label">Select Status :</label>
<div class="controls">
#Html.RadioButtonForEnum(n => n.Status)
</div>
</div>
</div>
Helper/extension.....
public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression
)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var names = Enum.GetNames(metaData.ModelType);
var sb = new StringBuilder();
foreach (var name in names)
{
var description = name;
var memInfo = metaData.ModelType.GetMember(name);
if (memInfo != null)
{
var attributes = memInfo[0].GetCustomAttributes(typeof(DisplayAttribute), false);
if (attributes != null && attributes.Length > 0)
description = ((DisplayAttribute)attributes[0]).Name;
}
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
name
);
var radio = htmlHelper.RadioButtonFor(expression, name, new { id = id }).ToHtmlString();
sb.AppendFormat(
"<label for=\"{0}\">{1}</label> {2}",
id,
HttpUtility.HtmlEncode(name),
radio
);
}
return MvcHtmlString.Create(sb.ToString());
}
The helper is displaying labels as it should having being called from the view.
Enum....
[Flags]
public enum NewsArticleStatus
{
[Display(Name = "Active")]
Active = 1,
[Display(Name = "InActive")]
Inactive = 2
}
Got it....
Added my original model(Article) to a viewModel and Added a bool property.... Active..
public bool Active
{
get
{
if (this.Article != null)
{
return (this.Article.Status == NewsArticleStatus.Active);
}
return false;
}
set
{
if (this.Article != null)
{
this.Article.Status = (value ? NewsArticleStatus.Active : NewsArticleStatus.Inactive);
}
}
}
Create the chkbox....
#Html.CheckBoxFor(n => n.Active)
So in the Controller simply assign the value to the new model
newNews.Status = model.Article.Status;
I have a mvc web project where I try to render a list of checkbox with the EditorFor extension method but the result just display the ids as text instead of of a list of checkbox.
Here is the code in the view:
<div id="permissions" class="tab-body">
#Html.Label("Permissions :")
#Html.EditorFor(x => Model.Permissions)
<br />
<br />
</div>
This is the property 'Permissions' of the object 'Model':
[DisplayName("Permissions")]
public List<PermissionViewModel> Permissions { get; set; }
And this is the PermissionViewModel:
public class PermissionViewModel
{
public int Id { get; set; }
public UserGroupPermissionType Name { get; set; }
public string Description { get; set; }
public bool IsDistributable { get; set; }
public bool IsGranted { get; set; }
}
And finally, this is the result in the browser:
<div id="permissions" class="tab-body" style="display: block;">
<label for="Permissions_:">Permissions :</label>
192023242526272829
<br>
<br>
</div>
Have you any idea why the html is not generated correctly? Missing dependencies? Conflict in dependencies? Web.Config configured not correctly?
Thank you very much for you help.
It looks as if you need to create an editor template for the "PermissionViewModel" class, as right now, MVC seems to be confused with how to make an editor for such a complex object.
In the folder where the view is being served from, add a folder called "EditorTemplates"
Then add a new partial view in that folder. The code should be:
#model IEnumberable<PermissionViewModel>
#foreach(var permission in Model)
#Html.EditorFor(x => x.Name)
#Html.EditorFor(x => x.Description)
#Html.EditorFor(x => x.IsDistributable)
#Html.EditorFor(x => x.IsGranted)
You will need to create an Editor Template for the Name class as well.
So now in your view you can call
<div id="permissions" class="tab-body">
#Html.Label("Permissions :")
#Html.EditorFor(x => Model.Permissions)
<br />
<br />
</div>
And MVC will know to use the editor template you just made for your permission.
A good resource for learning about editor templates is here: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-1-introduction.html
Maybe you want to make something yourself?
public delegate object Property<T>(T property);
public static HtmlString MultiSelectListFor<TModel, TKey, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, IEnumerable<TKey>>> forExpression,
IEnumerable<TProperty> enumeratedItems,
Func<TProperty, TKey> idExpression,
Property<TProperty> displayExpression,
Property<TProperty> titleExpression,
object htmlAttributes) where TModel : class
{
//initialize values
var metaData = ModelMetadata.FromLambdaExpression(forExpression, htmlHelper.ViewData);
var propertyName = metaData.PropertyName;
var propertyValue = htmlHelper.ViewData.Eval(propertyName).ToStringOrEmpty();
var enumeratedType = typeof(TProperty);
//check for problems
if (enumeratedItems == null) throw new ArgumentNullException("The list of items cannot be null");
//build the select tag
var returnText = string.Format("<select multiple=\"multiple\" id=\"{0}\" name=\"{0}\"", HttpUtility.HtmlEncode(propertyName));
if (htmlAttributes != null)
{
foreach (var kvp in htmlAttributes.GetType().GetProperties()
.ToDictionary(p => p.Name, p => p.GetValue(htmlAttributes, null)))
{
returnText += string.Format(" {0}=\"{1}\"", HttpUtility.HtmlEncode(kvp.Key),
HttpUtility.HtmlEncode(kvp.Value.ToStringOrEmpty()));
}
}
returnText += ">\n";
//build the options tags
foreach (TProperty listItem in enumeratedItems)
{
var idValue = idExpression(listItem).ToStringOrEmpty();
var displayValue = displayExpression(listItem).ToStringOrEmpty();
var titleValue = titleExpression(listItem).ToStringOrEmpty();
returnText += string.Format("<option value=\"{0}\" title=\"{1}\"",
HttpUtility.HtmlEncode(idValue), HttpUtility.HtmlEncode(titleValue));
if (propertyValue.Contains(idValue))
{
returnText += " selected=\"selected\"";
}
returnText += string.Format(">{0}</option>\n", HttpUtility.HtmlEncode(displayValue));
}
//close the select tag
returnText += "</select>";
return new HtmlString(returnText);
}
My model class:
public class StatusList
{
public int StatusID {get;set;}
[UIHint("ByteCheckbox")]
public byte Active {get;set;}
}
In /Views/Shared/EditorTemplates I created a file called ByteCheckbox.cshtml
The editortemplate ByteCheckbox contains (My 3rd attempt):
#model byte
#if (Model == 1)
{
#Html.CheckBox("", true)
}
else
{
#Html.CheckBox("", false)
}
Doing this nicely renders a checkbox. When I change the checkbox status and try to save the changes the model validation complains that the value is 'false' (or 'true') instead of the expected 0 or 1.
How to modify the editortemplate to allow for the value to be translated?
Have you tried this?
<div class="editor-label">
#Html.LabelFor(model => model.Active)
</div>
<div class="editor-field">
#Html.CheckBoxFor(model => model.Active != 0)
#Html.ValidationMessageFor(model => model.Active)
</div>
You can do this in your model:
public class StatusList
{
public int StatusID {get;set;}
public byte Active {get;set;}
[NotMapped]
public bool ActiveBool
{
get { return Active > 0; }
set { Active = value ? 1 : 0; }
}
}
Don't use Html.CheckBox; instead use Html.EditorFor. You'll need to define a file called ByteCheckbox.cshtml in Views/Shared/EditorTemplates for this to work as well.
You can also use a custom model binder.
Here's a sample for a decimal, but you can do it for the byte type.
public class DecimalModelBinder : DefaultModelBinder {
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
dynamic valueProviderResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (valueProviderResult == null) {
return base.BindModel(controllerContext, bindingContext);
}
return ((string)valueProviderResult.AttemptedValue).TryCDec();
}
}
try this one
#model bool
<div class="editor-for">
#Html.CheckBox("", Model, new{#class="tickbox-single-line"})
<div>
Try this:
#Html.CheckBox("Model", "Model")