Finding data associated with which <li> element the user has selected

I'm using MVC3 with razor view. I'm giving the user a list of <li>s to select from:

        <ol id="selectable">
            @foreach (var ebat in Model.AvailableSizes)
                <li class="ui-widget-content">@ebat.Item1 x @ebat.Item2</li>                    

where Model.AvailableSizes is a List<Tuple<int,int>>. When the user selects one of them, I want to be able to find from jQuery which Tuple<int,int> the user wants to use.

By the way I am using jqueryui Selectable with these list.

I guess I can find the selected element with $(".ui-selected:first"), but how can I get the associated Model data, namely @ebat.Item1 and @ebat.Item2, so that I can send them to the server as parameters?

I'm quite suspicious about my initial approach here, I mean it shouldn't be this hard. So if you could show me the better way to use model, html and jquery together in this kind of situations, it would be fantastic. Thanks.


Add attribute to li tag:

<li class="ui-widget-content" data="@ebat.Item1-@ebat.Item2">@ebat.Item1 x @ebat.Item2</li> 

Try the following jQuery Code:

    var value = $(".ui-selected:first").attr("data");
    var items = value.split("-");
    var item1 = items[0];
    var item2 = items[1];

You can add a hidden field for selected value and set its value on a select event.

@Html.HiddenFor(m => m.SelectedSize)

Although, Tuple<T1,T2> doesn't have a parameterless constructor so model binder can't create an instance. You can provide an integer ID for each size and read that when from the POST request.

You should use Tuple<int,T1,T2> for your AvailableSizes property. Also you have to save ID value as a custom attribute on li element so you can save it in the hidden field.

Still MVC will not be able to read AvailableSizes property on post request so you will have to exclude that property and read only SelectedSize property.

Here's how your model properties should look like:

public IEnumerable<Tuple<int,T1,T2>> AvailableSizes { get; set; }
public int SelectedSize { get; set; }

You should save Size ID as a custom attribute:

<ol id="selectable">
    @foreach (var ebat in Model.AvailableSizes)
        <li class="ui-widget-content" data-size-id="@ebat.Item1">@ebat.Item2 x @ebat.Item3</li>                    

You should provide the JavaScript for select events that should read the data-size-id attribute and set it to SelectedSize hidden field.

Need Your Help

Is there a better way than #if DebugMode for logging

c++ logging debugging

I'm making a c++ library thats going to be P/Invoked from c#, so i am unable to breakpoint/debug the c++ side of things. So i decided to add logging so i can see if anything goes wrong and where it