I am doing an Asp.Net Core Mvc 6 App.
I have and list of controls that represent the object of a page.
I have a class like this
public class RolesAccessModel
{
public string OptionMenu { get; set; } = string.Empty;
}
In this class I have several values
List<RolesAccessModel>lstRolesAccessModel=new();
RolesAccessModel RolesAccessModel=new();
RolesAccessModel="Button1";
lstRolesAccessModel.Add(RolesAccessModel );
RolesAccessModel RolesAccessModel2=new();
RolesAccessModel2="Button2";
lstRolesAccessModel.Add(RolesAccessModel2 );
RolesAccessModel RolesAccessModel3=new();
RolesAccessModel3="Button3";
lstRolesAccessModel.Add(RolesAccessModel3 );
I inherit this model in the View, where I have a lots of buttons and I have to make disable those buttons where the ID is in the Model
@model IEnumerable<ClientWeb.UI.Models.RolesAccessModel>
@{
ViewData["Title"] = "Employers";
}
<button type="button" id="Button1">Button1</button>
<button type="button" id="Button2">Button2</button>
<button type="button" id="Button3">Button3</button>
<button type="button" id="Button4">Button4</button>
<button type="button" id="Button5">Button5</button>
I do not want to do a foreach
(value in Model) foreach button
How can do that validation?
CodePudding user response:
where I have a lots of buttons and I have to make disable those buttons where the ID is in the Model
Do you want the way like below?
HomeController: add a new action DisableID
to pass the buttons in the Model in a json list, and use ajax to get the list:
public IActionResult Employers()
{
List<RolesAccessModel> lstRolesAccessModel = new List<RolesAccessModel>();
//...
return View(lstRolesAccessModel);
}
public IActionResult DisableID()
{
var lstRolesAccessModel = new List<RolesAccessModel>()
{
new RolesAccessModel{OptionMenu="Button1"},
new RolesAccessModel{OptionMenu="Button2"},
new RolesAccessModel{OptionMenu="Button3"}
};
return Json(lstRolesAccessModel);
}
Employers.cshtml: add below <script>
, use$(type = "button").each(function ()
to get the button ID and compare it with the list which contains the buttons in the Model :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("button").click(function () {
$.ajax(
{
type: "GET",
url: "/Home/DisableID",
success: function (data) {
for (var i = 0; i < data.length; i )
{
$(type = "button").each(function ()
{
if (this.id == data[i].optionMenu)
{$(this).attr('disabled', true); };
});
}
},
});
});
});
</script>
result: