.net mvc使用css3和html助手

时间:2016-05-09 19:53:50

标签: html asp.net-mvc css3

在我开始之前,我不确定我是否正确搜索了#34;我已经尝试了多个关于我将要解释的内容,但最终没有一个工作,因为我必须使用html助手。
我想要做的是使用ccs3创建自定义复选框。我找到了多个设计,我只是跟着他们,但我使用Html.CheckBoxFor(..., htmlAttributes: new { id = "A Number"})。 "数字"这里只是一个生成的数字,只是为了让我不做手动。

这是我处理自定义复选框(1)

的方式
<p>
            <input type="checkbox" value="..." id="@count" />                
                <label for="@count"><span class="ui"></span>Name</label>
            </p>

当我使用html帮助程序复选框时,当我使用它这种方式它不会工作我不知道为什么或我只是困惑它。 (2)

<p>
            @Html.CheckBoxFor(m => m..., htmlAttributes: new { id = count })

            <label for="@count"><span class="ui"></span>...</label>
        </p>

现在当我尝试(2)第一次它没有工作时我认为它来自我但是当我尝试时(1)它有效的奇迹期望当我提交它并不会返回复选框的值。当我搜索时,我发现这个Addind css classes to razor elements来自 darin-dimitrov 的回复很有意思,但我在我的视图中使用了一个自定义模板,简单地通过Layout = "..."调用它。答案的这一部分对我而言,我不知道如何宣布这个以及我如何打电话,如果它是独特的或改变了所有。
@Html.TextBox( "", ViewData.TemplateInfo.FormattedModelValue, ViewData )
css3代码

/*
    Custom Checkboxes
*/

[type="checkbox"]:not(:checked),
    input[type="checkbox"]:checked {
        position: absolute;  
        left: -9999px;
    }

[type="checkbox"]:not(:checked) + label,
    [type="checkbox"]:checked + label {
        position: relative;
        padding-left: 75px;
        cursor: pointer;
    }

    [type="checkbox"]:not(:checked) + label:before,
    [type="checkbox"]:checked + label:before,
    [type="checkbox"]:not(:checked) + label:after,
    [type="checkbox"]:checked + label:after {
        content: '';
        position: absolute;
    }
    [type="checkbox"]:not(:checked) + label:before,
    [type="checkbox"]:checked + label:before {
        left:0; top: -3px;
        width: 65px; height: 30px;
        background: #DDDDDD;
        border-radius: 15px;
        -webkit-transition: background-color .2s;
        -moz-transition: background-color .2s;
        -ms-transition: background-color .2s;
        transition: background-color .2s;
    }
    [type="checkbox"]:not(:checked) + label:after,
    [type="checkbox"]:checked + label:after {
        width: 20px; height: 20px;
        -webkit-transition: all .2s;
        -moz-transition: all .2s;
        -ms-transition: all .2s;
        transition: all .2s;
        border-radius: 50%;
        background: #7F8C9A;
        top: 2px; left: 5px;
    }

    /* on checked */
    [type="checkbox"]:checked + label:before {
        background:#34495E; 
    }
    [type="checkbox"]:checked + label:after {
        background: #39D2B4;
        top: 2px; left: 40px;
    }

    [type="checkbox"]:checked + label .ui,
    [type="checkbox"]:not(:checked) + label .ui:before,
    [type="checkbox"]:checked + label .ui:after {
        position: absolute;
        left: 6px;
        width: 65px;
        border-radius: 15px;
        font-size: 16px;
        font-weight: bold;
        line-height: 22px;
        -webkit-transition: all .2s;
        -moz-transition: all .2s;
        -ms-transition: all .2s;
        transition: all .2s;
    }
    [type="checkbox"]:not(:checked) + label .ui:before {
        content: "non";
        left: 32px
    }
    [type="checkbox"]:checked + label .ui:after {
        content: "oui";
        color: #39D2B4;
    }
[type="checkbox"]:focus + label:before {
    border: 1px dashed #777;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    -ms-box-sizing: border-box;
    box-sizing: border-box;
    margin-top: -1px;

更新
观点
如果需要视图,我可以提供解释

@model WebAppWithEF.Models.MainModel
@using WebAppWithEF.Models;

@{
    ViewBag.Title = "Page Title";
    Layout = "~/Views/Shared/_TemplateRest.cshtml"; 
}

@using (Html.BeginForm(null, "Export", new { entity_name = Model.which_entity_to_show }, FormMethod.Post, null))
{
    <div>
        <span class="text-uppercase">Nom Définition </span>
        @Html.EditorFor(m => m.exportDefinition.name, new { htmlAttributes = new { maxlength = "50" } })  <br />
        @if (Model.is_any_checked == false)
        {
            @Html.Label("Error MSG", htmlAttributes: new { @class = "text-danger" }) <br/>
        }
        <br />
        @for (int count = 0; count < Model.selectedFields.Count(); count++)
        {
            <p>
                @Html.CustomCheckBoxFor(m => m.selectedFields[count].propertyStatus)
                @Html.CustomLabelFor(m => m.selectedFields[count].propertyStatus, Model.selectedFields[count].propertyName, "<span class=\"ui\"></span>", new { @class = "class" })
            </p>
                @Html.HiddenFor(m => m.selectedFields[count].propertyStatus)
                @Html.HiddenFor(m => m.selectedFields[count].propertyName)
        }

        @Html.HiddenFor(m => m.exportDefinition.pkey)
        @Html.HiddenFor(m => m.exportDefinition.entityID)

        <div class="col-md-offset-0 col-md-10">
            <div class="contact-button">
                <button name="SaveDefinition" onclick="submit()">Enregistrer/Modifier</button>
            </div>
        </div>

        <div class="col-md-offset-0 col-md-10">
            <div class="contact-button">
                <button name="SpecificExport" onclick="submit()">Exporter</button>
            </div>
        </div>

        @if (!Model.is_new)
        {
            <div class="col-md-offset-0 col-md-10">
                <div class="contact-button">
                    <button name="DeleteDefinition" onclick="submit()">Supprimer</button>
                </div>
            </div>
        }

        <div class="col-md-offset-0 col-md-10">
            <div class="contact-button">
                <button onclick="@Url.Action("Index", "Home" , new { entity_name = ViewBag.entity_name })">Retour</button>
            </div>
        </div>
    </div>
}

2 个答案:

答案 0 :(得分:0)

其中一个问题是@Html.CheckBoxFor(....生成一个隐藏的输入,使得CSS规则变得混乱。第二个不要添加htmlAttributesid。您还需要在标签内添加span标记。

其他信息:Hidden input checkbox for,  Include inner element with HTML helper

解决方案:制作@Html.LabelFor()@Html.CheckBoxFor的两个附加信息:

更新:复选框扩展名不再需要隐藏输入类型

Checkbox扩展实施

public static class CheckboxExtensitons
{
    public static MvcHtmlString CustomCheckBoxFor<TModel, TValue>(
        this HtmlHelper<TModel> htmlHelper, 
        Expression<Func<TModel, TValue>> expression,
        object htmlAttributes = null)
    {
        var expressionText = ExpressionHelper.GetExpressionText(expression);
        var htmlAtributesDictionary = new RouteValueDictionary(htmlAttributes);
        // TagBuilder hidden = new TagBuilder("input");
        // hidden.Attributes.Add("type", "hidden");
        // hidden.Attributes.Add("name", expressionText);
        // hidden.Attributes.Add("value", "false");

        TagBuilder input = new TagBuilder("input");
        input.Attributes.Add("type", "checkbox");
        input.Attributes.Add("name", expressionText);
        input.Attributes.Add("id", expressionText);
        input.Attributes.Add("value", "true"); // update
        input.MergeAttributes(htmlAtributesDictionary);

        MvcHtmlString result = MvcHtmlString.Create(input.ToString());
        return result;
    }
}

标签扩展实施

public static class LabelExtensions
{
    public static MvcHtmlString CustomLabelFor<TModel, TPropery>(
        this HtmlHelper<TModel> htmlHelper,
        Expression<Func<TModel, TPropery>> expression, 
         string labelValue,
        string innerHtml,
        object htmlAttributes = null)
    {
        TagBuilder tag = new TagBuilder("label");
        var htmlAtributesDictionary = new RouteValueDictionary(htmlAttributes);
        //Add the specified Html attributes
        tag.MergeAttributes(htmlAtributesDictionary);

        var expressionText = ExpressionHelper.GetExpressionText(expression);
        tag.Attributes.Add("for", expressionText);
        tag.InnerHtml = innerHtml + labelValue;
        return MvcHtmlString.Create(tag.ToString());
    }
}

我使用此模型,视图和控制器操作进行了测试:

<强>型号:

public class TeamChoice
{
    public bool TeamCap { get; set; }

    public bool TeamIronMan { get; set; }
}

操作:

public ActionResult Team()
{
    var model = new TeamChoice();
    return this.View(model);
}

[HttpPost]
public ActionResult Team(TeamChoice model)
{
    return this.RedirectToAction("Team");
}

查看:

@model TeamChoice
@using Namespace.OfExtensions; // Important!
@using (Html.BeginForm("Team","Home", FormMethod.Post, null))
{
    <p>
        @Html.CustomCheckBoxFor(a => a.TeamCap)
        @Html.CustomLabelFor(m => m.TeamCap, "Team Cap", "<span class=\"ui\"></span>", new { @class = "class" })
    </p>
    <p>
        @Html.CustomCheckBoxFor(m => m.TeamIronMan)
        @Html.CustomLabelFor(m => m.TeamIronMan, "Team Iron Man", "<span class=\"ui\"></span>", new { @class = "class" })
    </p>
<input type="submit" />
}

答案 1 :(得分:0)

我会在这里发布一些代码,以便在更新后匹配您的模型和视图。

更新后,我有一些问题。 我改变了我的代码如下:

public ActionResult Team()
{
    var model = new TeamChoice();
    model.exportDefinition = new exportDefinition()
    {
        entityID = "8831A386-18D6-4EAE-919E-9C1D316CC2DD",
        name = "EntryName",
        pkey = "PKeyu"
    };

    model.is_any_checked = true;
    model.which_entity_to_show = "MineEntry";
    model.is_new = false;
    model.selectedFields = new List<Field>();
    for (int i = 1; i <= 15; i++)
    {
        model.selectedFields.Add(new Field()
        {
            propertyName = "Property" + i,
            propertyStatus = i % 2 == 0 ? false : true   
        });
    }

    return this.View(model);
}

[HttpPost]
public ActionResult Team(TeamChoice model)
{
    // this.Request.Form: 
    // exportDefinition.name=EntryName&selectedFields[0].propertyStatus=true&
    // selectedFields[0].propertyStatus=False&selectedFields[0].propertyName=Property1&
    // selectedFields[1].propertyStatus=true&selectedFields[1].propertyStatus=False&
    // selectedFields[1].propertyName=Property2&selectedFields[2].propertyStatus=true&
    // selectedFields[2].propertyStatus=False&selectedFields[2].propertyName=Property3&
    // selectedFields[3].propertyStatus=False&selectedFields[3].propertyName=Property4& and so on....
    // First tree fields in the collection will have status "true"
    var propertyStatus1 = model.selectedFields[0].propertyStatus;
    var propertyStatus2 = model.selectedFields[1].propertyStatus;
    var propertyStatus3 = model.selectedFields[2].propertyStatus;

    return this.RedirectToAction("Team");
}

将模型传递给视图时,是否在任何字段的propertyStatus中设置了“true”?第二,你可以验证当你检查第一个树复选框“Oui”并提交表格时你是否有如下所示的表格数据?

selectedFields[0].propertyStatus=true& selectedFields[1].propertyStatus=true& selectedFields[2].propertyStatus=true& selectedFields[3].propertyStatus=false ....

更新将您的复选框扩展程序更新为以下代码。当您在True中传递propertyStatus时,将会检查HTML中的复选框。

public static MvcHtmlString CustomCheckBoxFor<TModel>(
        this HtmlHelper<TModel> htmlHelper, 
        Expression<Func<TModel, bool>> expression,
        object htmlAttributes = null)
{
    var expressionText = ExpressionHelper.GetExpressionText(expression);
    var htmlAtributesDictionary = new RouteValueDictionary(htmlAttributes);

     TagBuilder input = new TagBuilder("input");
     input.Attributes.Add("type", "checkbox");
     input.Attributes.Add("name", expressionText);
     input.Attributes.Add("id", expressionText);
     input.Attributes.Add("value", "True");
     input.Attributes.Add("data-val", "True");

     ModelMetadata modelMetadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
     bool value;
     if (modelMetadata.Model != null && bool.TryParse(modelMetadata.Model.ToString(), out value))
     {
         if (value)
         {
             input.Attributes.Add("checked", "checked");
         }
     }


     MvcHtmlString result = MvcHtmlString.Create(input.ToString());
     return result;
 }

并将您的视图@Html.HiddenFor(m => m.selectedFields[count].propertyStatus)替换为@Html.Hidden("selectedFields[" + count + "].propertyStatus", false)