User1686398519 posted
Hi tinac99,
tinac99
Is there anyway for me to attach a [Required] attribute in the property of the class at runtime before rendering the views?
As far as I know, this idea is almost impossible to achieve, but I have a solution to achieve your needs. If you are willing to try it, you can refer to this example.
- You can use the required method to make the element necessary.
- You need to reference the "jquery.min.js" file.
Model
public class Test1ViewModel
{
public string Id { get; set; }
public string name { get; set; }
}
Controller
public IActionResult Test1()
{
return View();
}
public IActionResult Test2()
{
return View();
}
[HttpPost]
public IActionResult Test3(Test1ViewModel test1)
{
return View();
}
Test1
<h1>Id is not required</h1>
@Html.ActionLink("To Test2", "Test2", "Test6")
@await Html.PartialAsync("PartialTest")
Test2
<h1>Id is required</h1>
@Html.ActionLink("To Test1", "Test1", "Test6")
@await Html.PartialAsync("PartialTest")
@section scripts{
<script>
$(function () {
$("#Id").attr("required", "true");
});
</script>
}
Test3
<h1>Success</h1>
@Html.ActionLink("To Test2", "Test2", "Test6")
@Html.ActionLink("To Test1", "Test1", "Test6")
PartialTest
@model WebApplication7.Models.Test1ViewModel
@using (Html.BeginForm("Test3", "Test6", FormMethod.Post))
{
<div class="form-group row">
@Html.LabelFor(m => m.Id, new { @class = "col-sm-2 col-form-label" })
<div class="col-sm-10">
@Html.TextBoxFor(m => m.Id, new { @class = "form-control" })
</div>
</div>
<div class="form-group row">
@Html.LabelFor(m => m.name, new { @class = "col-sm-2 col-form-label" })
<div class="col-sm-10">
@Html.TextBoxFor(m => m.name, new { @class = "form-control" })
</div>
</div>
<button type="submit">submit</button>
}
Here is the result.

Best Regards,
YihuiSun