views:

2208

answers:

3

While rendering the view page, based on some condition in the controller action I want to disable all the controls (textbox, checkbox, button etc) present in the form in a MVC view page. Is there any way to do that? Please help.

A: 

I don't think you can do that from the controller, since the view is returned after all the other logic is done. You could probably do something, however, with the AJAX libraries included with ASP.NET MVC.

Annath
+3  A: 

you can pass a flag to the view to indcate that it must disable all the 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>
Marwan Aouida
.............. jQuery rockz!
cottsak
It worked for me... Thanks
Ravi
+1  A: 

That really depends on how your controls are being rendered. We do something similar in practice, except we set controls to read only. This is to allow us to re-use show (read-only) and edit views.

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

From there, write some helper methods to distinguish between disabled and non-disabled markup. You can build this markup yourself, or wrap the existing HtmlHelper methods ASP.NET MVC provides.

// 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);
}

The way we do it is to use the Page_Load(), as you would in WebForms, to disable server controls. We built some custom server controls to handle our form fields. This was in ASP.NET MVC's infancy, and I wouldn't recommend doing this, but it's an alternative.

Stuart Branham