Richard77
Richard77

Reputation: 21661

How can I access attributes of Html elements in ASP.NET MVC

With ASP.NET Webforms, I could drag and drop a control on a form and be able to access its properties:

if (number == 0)
   AddButton.Enabled = false;

Although I cannot drag and drop a control on a ASP.NET MVC View template, can I change its attributes?

For instance:

Upvotes: 2

Views: 13621

Answers (6)

George Stocker
George Stocker

Reputation: 57907

There are (at least) two Methods to do this:

Method 1: The Simple Way

You would do this by adding logic in your view:

<input type="button" disabled=<%= Model.number <= 0 %> />

Where Model.number is the count of items passed to your view by your controller. If it's less than or equal to zero, disabled will be true.

The syntax may not be exact, I haven't tried this, but this is the path I would go down to do what you want.

This will work for the initial setting of the value; changing it without refreshing the page is a matter of using JavaScript, as other answers have pointed out.

Method 2: The overly complex but more 'MVC' way

If you want the logic in the controller rather than the view, you should set up a specific ViewModel object that you can add the logic to:

ViewModel

public class MyObjectViewModel
{
    MyObject MyObject {get; private set; }
    bool Enabled; {get; set; }
    public MyObjectViewModel(MyObject obj)
    {
        MyObject = obj;
    }
    string IsEnabled
    {
        get
        {
             if (Enabled)
             {
                 return "";
             }
             else return "disabled=disabled";
        }
    }

Controller

public ActionResult Show(int id)
{
    MyObject myObject = repository.GetMyObjectById(id)
    MyObjectViewModel movm = myObject; 
    movm.Enabled = myObject.number > 0;
    return View(movm);
}

View

<input type="button" <%= Model.IsEnabled %> />

Again, the syntax and usage may be a little off, I'm prototyping this off the top of my head, and am not in a location where I can test this for you.

If you're interested in ViewModels, here are some good resources:

I've updated it to return disabled=disabled using the string if it is actually disabled.

Upvotes: 4

Richard77
Richard77

Reputation: 21661

As I replied to George Stocker, I've noticed that the disabled attribute can get only 1 value (disabled = "disabled"). Also, anything else disable the input control as well. For instance, disabled = true and disable = false will still disable the control.

It looks like (I'm not sure) having disabled attribute disables the control and not having it enables the control. So I decided to write a extension method to the HtmlHelper class.

public static class MyHelperClass
{
  public static string InputDisable(this HtmlHelper html, string name, string myValue,     bool isEnabled)
  {
    string show = "";
    if(!isEnable)
       show = "disabled = \"disabled\"";
    return "<input type = \"submit\" value = \"" + myValue + "\"" + show + " />";
  }
}

Now I can access the method this way

<% = Html.InputDisable("myInput", "My Button", false)%>

So the last param determines weather the input control is visible.

Now using the Goerge Stocker logical, I can define the value of isEnabled .

Thanks for all your answers

Upvotes: 0

Mark
Mark

Reputation: 10206

I would check out the HTML helpers.

<%= Html.Button("AddButton","Button Text",HtmlButtonType.Submit,"SomeJavaScriptFunction()",new {disabled="disabled"} )  %>

The only real gotcha is the anonymous class at the end gets funny when you add attributes that are keywords. For example, to add a Css class you need an anonymous class that looks like this new {@class="myCssClassName"}.

Upvotes: 0

Soraz
Soraz

Reputation: 6756

All client side behaviour is scripted through javascript. MVC default ships with jQuery for this (www.jquery.com).

I've outlined how you could go about your examples:

<input id="nextFinishBtn" type="button" value="Next ->"/>

Assume you want to change this to "Finish" if the user unchecks a checkbox named "Configure Advanced settings". which was true by default

<%= Html.CheckBox("DoAdvancedSettings", "true", new { onclick='changeNextButton()' }); %>
<script langauge="javascript">
    function changeNextButton() {
        $('#nextFinishBtn').val('Finish');
    }
</script>

In general you can access any attribute of any element in jQuery using the .attr construct:

$('#nextFinishBtn').attr('disabled','disabled');

You call it with two parameters to set a value, and with just one to fetch the value. So to see if the button is disabled, you'd do:

if ($('#nextFinishBtn').attr('disabled')=='disabled') { alert('button is disabled'); }

Upvotes: 2

Jonas H&#248;gh
Jonas H&#248;gh

Reputation: 10884

Generally, you rarely want to do this. The MVC way is:

  1. Let your controller populate the model with the objects needed to generate the HTML
  2. Pass the model to the appropriate view
  3. Let the view output the HTML based on the values of the objects in the model.

If you often find yourself in need of modifying HTML attributes after the HTML has been generated, you're probably not applying this pattern correctly.

Upvotes: 0

Tom Cabanski
Tom Cabanski

Reputation: 8018

ASP.NET MVC is a lightweight programming model. It does not create a control object model for you at the server the way plain ASP.NET does. Typically, you would use client-side javascript (possibly with help from JQuery) to manipulate the properties of controls that are put on the page by the markup in your view.

If you want to get a quick start with ASP.NET MVC, check out Sharp Architecture (open source). They have guidance and all sorts of goodies to help you get productive with ASP.NET MVC quickly.

Upvotes: 0

Related Questions