I'm using MVC 3 and Razor
At the moment I'm using
@model MyProject.ViewModels.MyViewModel @foreach (var item in Model.MyProperty) { <tr> <td> @Html.ActionLink("Edit", "Edit", new { id = item.AdvSlotId }) | @Html.ActionLink("Details", "Details", new { id = item.AdvSlotId }) | @Html.ActionLink("Delete", "Delete", new { id = item.AdvSlotId }) </td> <td> @item.AdvSlotId </td> <td> @item.Name </td> <td> @item.Description </td> <td> @Html.CheckBox(item.IsPublished, new { @disabled = "disabled" }) </td> <td> @item.Notes </td> </tr> }
The VIEW MODEL:
namespace MyProject.ViewModels { public class MyViewModel { public MyViewModel(List<AdvSlot> advSlots) { MyProperty= advSlots; } public List<AdvSlot> MyProperty { get; set; } } }
To display a Check Box for a property in my Model. As I'm doing is wrong so I can only display a text like TRUE.
Could you please tell me how to create the CheckBox with Razor? I would also need have it as READONLY.
Thanks for your help.
//This will make all read-only check boxes truly read-only $('input[type="checkbox"][readonly]'). on("click. readonly", function(event){event. preventDefault();}).
The CheckBox is made ReadOnly by making it Non-Clickable by adding JavaScript OnClick event handler and returning False.
Razor offers two ways to generate checkboxes. The recommended approach is to use the input tag helper. Any boolean property of the PageModel will render a checkbox if it is passed to the asp-for attribute, so long as the property is not nullable: public class IndexModel : PageModel.
$(':checkbox[readonly]'). click(function(){ return false; });
Should be something like this:
@Html.CheckBoxFor(m => m.IsPublished, new { @disabled = "disabled" })
UPDATE:
Assuming that your class AdvSlot
contains a property IsPublished
you can write in your loop:
<td> @Html.CheckBox(item.AdvSlotId + "_IsPublished", item.IsPublished, new { @disabled = "disabled" }); </td>
@Html.CheckBoxFor(model => model.IsActive, new { onclick = "return false" })
This should work. However i got a problem with @disabled = "disabled". If i make the checkbox checked by default and make the checkbox disabled at the same time it wont post with its value. At controller it will get false. Using "return false" user wont able to change the value and it will also post the value which has set on load as by default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With