I have a class which is used in a PartialView. This class is used in a ViewModel. There are 2 views which use the partial view. In view1, some properties are required entries. In view2, these are not required.
Is there anyway for me to attach a [Required] attribute in the property of the class at runtime before rendering the views?
attributes are compile time attributes, so they can not change at runtime. you count use custom validation attibutues that look at other properties to determine. google if validation. you could have two view models.
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")
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
Member
48 Points
291 Posts
Attach Required Attribute to To A Property At Runtime
Aug 03, 2020 10:59 PM|tinac99|LINK
Hello,
I have a class which is used in a PartialView. This class is used in a ViewModel. There are 2 views which use the partial view. In view1, some properties are required entries. In view2, these are not required.
Is there anyway for me to attach a [Required] attribute in the property of the class at runtime before rendering the views?
I'm using MVC, ASP Core 2.0.
Thanks!
tinac99
All-Star
58124 Points
15635 Posts
Re: Attach Required Attribute to To A Property At Runtime
Aug 04, 2020 12:06 AM|bruce (sqlwork.com)|LINK
attributes are compile time attributes, so they can not change at runtime. you count use custom validation attibutues that look at other properties to determine. google if validation. you could have two view models.
Contributor
2690 Points
771 Posts
Re: Attach Required Attribute to To A Property At Runtime
Aug 04, 2020 07:07 AM|YihuiSun|LINK
Hi tinac99,
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.
Model
Controller
Test1
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
PartialTest
Here is the result.
Best Regards,
YihuiSun