Home > OS >  incorrect radio button set as "checked"
incorrect radio button set as "checked"

Time:12-20

Newbie question, please be kind.

I have this Index.cshtml page in C# MVC application. When the page is rendered, the last button is checked. How do I make the first button (All) set to checked instead?

I am reading thru the "similar questions", but none seem to address my question. Please help. Thank you in advance if you can explain this to me.

<h1>@ViewBag.title</h1>

<form action="/list/index" method="post">
    <h2>Search by:</h2>

    <p>
        @foreach (var column in ViewBag.columns)
        {
            <span>
                <input type="radio" name="searchType" id="@column.Key" value="@column.Key" checked="@column.Key == 'all'" />
                <label for="@column.Key">@column.Value</label>
            </span>
        }
    </p>

    <p>
        <label for="searchTerm">Keyword:</label>
        <input type="text" name="searchTerm" id="searchTerm" />
    </p>

    <input type="submit" value="Search" />
</form>

<hr />

@if (ViewBag.service != null)
{
    <table>
        @foreach (var srv in ViewBag.service)
        {
            <tr>
                <td>
                    <p>Provider: @srv.Provider.Name</p>
                    <p>Location: @srv.Location.Address</p>
                    <p>Category: @srv.Category.Name</p>
              @*      <p>Tag: @service.Tag</p>
                    <p>Keyword: @service.Keyword</p>*@
                </td>
            </tr>
        }
    </table>
}

CodePudding user response:

In one condition:

<input type="radio" name="searchType" id="@column.Key" value="@column.Key" @(column.Key == 'all' ? "checked" : " ") />

Checked or not checked?

CodePudding user response:

You can just use checked for checked any radio button:

<input type="radio" checked />

For conditionally check any of your radio button, use this:

@if(column.Key == 'all'){
 <input type="radio" name="searchType" id="@column.Key" value="@column.Key" checked />
}else{
 <input type="radio" name="searchType" id="@column.Key" value="@column.Key" />
}
  • Related