Disable all controls (text box, check box, button, etc.) in the view (ASP.NET MVC)

When rendering a view page based on some condition in the controllerโ€™s action, I want to disable all the controls (text box, check box, button, etc.) presented in the form on the MVC view page. Is there any way to do this? Please, help.

+6
c # asp.net-mvc
source share
3 answers

you can pass a flag to the view to indicate that it should disable all controls.

here is an example:

public ActionResult MyAction() { ViewData["disablecontrols"] = false; if (condition) { ViewData["disablecontrols"] = true; } return View(); } 

In the view (using jQuery):

  <script type="text/javascript"> $(document).ready(function() { var disabled = <%=ViewData["disablecontrols"].ToString()%>; if (disabled) { $('input,select').attr('disabled',disabled); } }) </script> 
+10
source share

It really depends on how your controls are displayed. In practice, we do something similar, except that we install read-only controls. This will allow us to reuse show (read-only) and edit views.

The way I personally would recommend doing this is to have a read-only flag that is set in the view using the value in ViewData.

From there write some helper methods to distinguish between disabled and uninfected markup. You can create this markup yourself or wrap existing HtmlHelper methods provided by ASP.NET MVC.

 // In your controller ViewData["DisableControls"] = true; <%-- In your view --%> <% bool disabled = ViewData["DisableControls"] as bool; %> ... <%= Html.TextBox("fieldname", value, disabled) %> <%= Html.CheckBox("anotherone", value, disabled) %> // In a helper class public static string TextBox(this HtmlHelper Html, string fieldname, object value, bool disabled) { var attributes = new Dictionary<string, string>(); if (disabled) attributes.Add("disabled", "disabled"); return Html.TextBox(fieldname, value, attributes); } 

As we do this, use the Page_Load () function, as in WebForms, to disable server controls. We have created some custom server controls for processing form fields. This was in early childhood ASP.NET MVC, and I would not recommend doing this, but it is an alternative.

+1
source share

I do not think you can do this from the controller, since the view is returned after another logic is executed. Perhaps you could do something with the AJAX libraries included with ASP.NET MVC.

0
source share

All Articles