Asp.net core mvc how to set attribute 'required' via razor

Viewed 1031

I have a form in mvc where different fields settings are controlled from database.

I have written a razor function which checks if certain fields are mandatory.

In case of true I need to set the required attribute. Currently I can't call razor function in input tag.

What are my options?

<input type="text" class="form-control" asp-for="@Model.Title" required="@myfunction()" maxlength="200" />
2 Answers

You can create a tag helper for this type of situation like below

    private const string ForAttributeName = "asp-for";

    [HtmlAttributeName("asp-is-required")]
    public bool IsMandatory { set; get; }

    public InputTextRequired(IHtmlGenerator generator) : base(generator)
    {
    }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        if (IsMandatory)
        {
            var attribute = new TagHelperAttribute("required");
            output.Attributes.Add(attribute);
        }
        base.Process(context, output);
    }
}

You can use that tag helper in your input tag like below

<input type="text" class="form-control" asp-for="@Model.Title" asp-is-required="true/false from razor" maxlength="200" />

More info on Tag Helper use this link

If I understand correctly, you have your required parameter saved in database, so you can pass it from back end. I would recommend use Viewbag and send it to view from you controller. enter image description here

Then you can set required tag. enter image description here

Related