How to pass string value for asp-for in asp net 5

I want to write an Edit.cshtml file for an object with many properties for editing, 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>

In fact, there are many objects, so I have to write many Edit.cshtml files. I want to make some simplifications

I want to select some properties of an object in a controller and use a loop to display properties in a 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);
}

In the view file:

@{
    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>
    }
}

but it cannot work as it generates the wrong codes. It seems like I can't pass the string value to the asp-for tag helper.

For example, if I changed the vertex code 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>
}

The above code 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>

Expected Code:

<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>

How do i do

Is this possible in a razor?

+7
3

, . : , , . , , , , , .

:

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; }
    }
}

. , "". , Process...

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, aspFor.ModelExplorer, 
                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 ):

@addTagHelper "*, WebApplication1"

, (, , ?):

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);
}

, , - :

<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>
+8

, . , . "type", type='text'. data-val, "-" "_" Ex: @data_val_email

<div class="form-group">
  @Html.LabelFor(x=>x.Email)
  <div class="col-md-10">
     @Html.TextBoxFor(x => x.Email, new { @class = "form-control", @type = "email" })
      @Html.ValidateFor(x=>x.Email)
  </div>
</div>
0

. , HTML- . ASP.NET MVC EditorTemplate.

,

public class MyFormGroupTagHelper : PartialTagHelper
{
    public MyFormGroupTagHelper(ICompositeViewEngine viewEngine, IViewBufferScope viewBufferScope) : base(viewEngine, viewBufferScope)
    { }

    public ModelExpression Property { get; set; }

    public string LabelText { get; set; } = null;

    public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
    {
        this.For = Property;
        this.Name = "_FormGroup";
        // Have to use Viewdata to pass information to the partial view, because the model is the single property of the entity that will be posted back to the controller
        this.ViewData["TH_LabelText"] = LabelText;
        this.ViewData["TH_DataTypeName"] = Property.Metadata.DataTypeName;
        await base.ProcessAsync(context, output);
    }
}

_FormGroup.cshtml. Bootstrap. datepicker , . , asp-for @Model,

@model object

@{
    string LabelText = (string)@ViewData["TH_LabelText"];
    string DataTypeName = (string) ViewData["TH_DataTypeName"];
    bool IsDate = (DataTypeName == "Date");
}

<div class="form-group row">
    @if (LabelText != null)
    {
    <label asp-for="@Model" class="control-label col-md-4">@LabelText</label>
    }
    <div class="col-md-8">
        <input asp-for="@Model" class="form-control @( IsDate ? "datepicker" : "")"  />
        <span asp-validation-for="@Model" class="text-danger"></span>
    </div>
</div>

"" "", -, , .

<my-form-group label-text="Result date" property="ResultDate" view-data="ViewData" ></my-form-group>

ResultDate, :

    [DataType(DataType.Date)]
    public DateTime? ResultDate { get; set; }

, view-data ViewData . ViewData . , - . "TH_", Viewdata.

0

Source: https://habr.com/ru/post/1620050/


All Articles