如何传递字符串值" ASP-的"在ASP网5 [英] How can I pass string value for "asp-for" in asp net 5

查看:216
本文介绍了如何传递字符串值" ASP-的"在ASP网5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写的许多属性编辑实体Edit.cshtml文件,所以我写了下面的codeS多次:

I want to write a Edit.cshtml file for an entity with many properties to edit, so I have to write the following codes many times:

<div class="form-group">
    <label asp-for="Email" class="col-md-2 control-label"></label>
    <div class="col-md-10">
        <input asp-for="Email" class="form-control" />
        <span asp-validation-for="Email" class="text-danger"></span>
    </div>
</div>

其实,有许多实体,使我不得不写了许多Edit.cshtml文件。我想要做一些简化

Actually, there are many entities so that I have to write many Edit.cshtml files. I want to make some simplifications

我想在控制器中选择实体的某些属性,并使用循环显示视图的属性。例如:
在控制器文件:

I want to select some properties of the entity in the controller and use loop to show the properties in the view. For example: In the controller file:

public IActionResult Edit(string id)
{
    var model = GetModel(id);
    var propertyNames= new List<string>()
    {
        "Name",
        "Email"
        // add some other property names of the entity 
    };
    ViewData["PropertyList"] = propertyNames;
    return View(model);
}

在视图文件:

@{
    var propertyNames = (List<string>)ViewData["PropertyList"];
    foreach (string item in propertyNames)
    {
        <div class="form-group">
            <label asp-for="@(item)" class="col-md-2 control-label"></label>
            <div class="col-md-3">
                <input asp-for="@(item)" class="form-control" />
                <span asp-validation-for="@(item)" class="text-danger"></span>
            </div>          
        </div>
    }
}

但它不能正常工作,因为它会产生错误的codeS。看来,我不能为ASP换标签帮手传递一个字符串值。

例如,如果我改变顶部code这样:

For example, if I change the code of top to this:

@{
    string e = "Email";
    <div class="form-group">
        <label asp-for="@e" class="col-md-2 control-label"></label>
        <div class="col-md-10">
            <input asp-for="@e" class="form-control" />
            <span asp-validation-for="@e" class="text-danger"></span>
        </div>
    </div>
}

在code以上会产生这样的:

The code above will generate this:

<div class="form-group">
    <label class="col-md-2 control-label" for="e">e</label>
    <div class="col-md-10">
        <input class="form-control" type="text" id="e" name="e" value="Email" />
        <span class="text-danger field-validation-valid" data-valmsg-for="e" data-valmsg-replace="true"></span>
    </div>
</div>

预期code是:

The expected code is:

<div class="form-group">
    <label class="col-md-2 control-label" for="Email">Email</label>
    <div class="col-md-10">
        <input class="form-control" type="email" data-val="true" data-val-email="Email &#x5B57;&#x6BB5;&#x4E0D;&#x662F;&#x6709;&#x6548;&#x7684;&#x7535;&#x5B50;&#x90AE;&#x4EF6;&#x5730;&#x5740;&#x3002;" data-val-required="Email &#x5B57;&#x6BB5;&#x662F;&#x5FC5;&#x9700;&#x7684;&#x3002;" id="Email" name="Email" value="" />
        <span class="text-danger field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"></span>
    </div>
</div>

我应该怎么办?

是否有可能在剃刀?

推荐答案

好吧,我设法得到这个工作。 免责声明:这是超级哈克,我不知道如果我在最好的方式做到了。我所知道的是,你想要做什么,它可能指向你在正确的方向。

Ok, I managed to get this working. DISCLAIMER: It is super hacky and I have no idea if I've done it in the best way possible. All I know is that it does what you want and it might point you in the right direction.

首先,我创建了一个模型:

Firstly, I created a model:

using System.ComponentModel.DataAnnotations;

namespace WebApplication1.Models
{
    public class TestModel
    {
        [Required]
        public string Name { get; set; }

        [Required]
        [EmailAddress]
        [Display(Name = "Email Address")]
        public string Email { get; set; }
    }
}

然后,我做了一个自定义标签帮手。这是可怕的位,其中神奇发生。特别是过程方法的第一部分...

Then, I made a custom tag helper. This is the horrible bit where the "magic" happens. Specifically the first section of the Process method...

using Microsoft.AspNet.Mvc.Rendering;
using Microsoft.AspNet.Mvc.ViewFeatures;
using Microsoft.AspNet.Razor.TagHelpers;
using System.Linq;

namespace WebApplication1.TagHelpers
{
    [HtmlTargetElement("edit")]
    public class EditTagHelper : TagHelper
    {
        [HtmlAttributeName("asp-for")]
        public ModelExpression aspFor { get; set; }

        [ViewContext]
        [HtmlAttributeNotBound]
        public ViewContext ViewContext { get; set; }

        protected IHtmlGenerator _generator { get; set; }

        public EditTagHelper(IHtmlGenerator generator)
        {
            _generator = generator;
        }

        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            var propName = aspFor.ModelExplorer.Model.ToString();
            var modelExProp = aspFor.ModelExplorer.Container.Properties.Single(x => x.Metadata.PropertyName.Equals(propName));
            var propValue = modelExProp.Model;
            var propEditFormatString = modelExProp.Metadata.EditFormatString;

            var label = _generator.GenerateLabel(ViewContext, aspFor.ModelExplorer,
                propName, propName, new { @class = "col-md-2 control-label", @type = "email" });

            var input = _generator.GenerateTextBox(ViewContext, aspFor.ModelExplorer,
                propName, propValue, propEditFormatString, new { @class = "form-control" });

            var validation = _generator.GenerateValidationMessage(ViewContext, propName,
                string.Empty, string.Empty, new { @class = "text-danger" });

            var inputParent = new TagBuilder("div");
            inputParent.AddCssClass("col-md-10");
            inputParent.InnerHtml.Append(input);
            inputParent.InnerHtml.Append(validation);

            var parent = new TagBuilder("div");
            parent.AddCssClass("form-group");
            parent.InnerHtml.Append(label);
            parent.InnerHtml.Append(inputParent);

            output.Content.SetContent(parent);
            base.Process(context, output);
        }
    }
}

NB :为了使定制TagHelper工作,你需要添加一行到 _ViewImports.cshtml 文件,就像这样(把 WebApplication1 与命名空间):

NB: To make the custom TagHelper work, you need to add a line into the _ViewImports.cshtml file, like this (replace WebApplication1 with your namespace):

@addTagHelper "*, WebApplication1"

我改变了我的行动,这一点,那种满足你(也许你可以使用反射来这里得到你的模型属性名):

I changed my action to this, to sort of match yours (maybe you can use reflection to get your model property names here?):

public IActionResult Index()
{
    var propertyNames = new List<string>()
    {
        "Name",
        "Email"
    };
    ViewData["PropertyList"] = propertyNames;

    var m = new TestModel()
    {
        Name = "huoshan12345",
        Email = "test@test.net"
    };
    return View(m);
}

于是最后,在视图中,你可以做这样的事情:

Then finally, in the view, you can do something like this:

<div class="row">
    @using (Html.BeginForm())
    {
        var propertyNames = (List<string>)ViewData["PropertyList"];
        foreach (string item in propertyNames)
        {
            <edit asp-for="@item"></edit>
        }
        <input type="submit" value="Submit" />
    }
</div>

这篇关于如何传递字符串值&QUOT; ASP-的&QUOT;在ASP网5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆