User987
User987

Reputation: 3823

Setting radio button default selected option in CSHTML Razor .NET

I have a HTML markup like this:

<input type="radio" name="shipping" value="Worldwide"> All Locations<br>
<input type="radio" name="shipping" value="US" checked> US Only<br>
<input type="radio" name="shipping" value="GB"> UK Only


<input type="radio" name="type" value="all"> All Listings
<input type="radio" name="type" value="FixedPrice" checked> Fixed Price
<input type="radio" name="type" value="Auction"> Auction




   <input type="radio" name="condition" value="New" checked> Brand New<br>
                <input type="radio" name="condition" value="Used"> Used<br>

Basically what I'm trying to do here is save user preferences and then load them from my DB into these checkboxes like this:

 @if (ViewBag.UserPreferences!=null)
        {

        @:$("input[name='shipping'][value='" + @ViewBag.UserPreferences.ShippingLocation + "']").attr('checked', 'checked');
        @:$("input[name='type'][value='" + @ViewBag.UserPreferences.ListingType + "']").attr('checked', 'checked');
        @:$("input[name='condition'][value='" + @ViewBag.UserPreferences.Condition + "']").attr('checked', 'checked');


        }

Contents of `ViewBag.UserPreferences are exactly equal to the values that u see in value attribute of either of these tags up there.

What am I doing wrong here???

Upvotes: 0

Views: 2051

Answers (1)

Eric G
Eric G

Reputation: 2617

You shouldn't need to escape from the single quotes to add the razor value. Try this:

@:$("input[name='shipping'][value='@ViewBag.UserPreferences.ShippingLocation']").attr('checked', 'checked');

And I have also had luck with <text>:

<text>$("input[name='shipping'][value='@ViewBag.UserPreferences.ShippingLocation']").attr('checked', 'checked');</text>

Upvotes: 1

Related Questions