mardi 27 février 2018

MVC radio button checked based on database field value

MVC app for logging time spent at clients. I have a radio with four choices: Regular, Overtime, Doubletime & Free In the create & edit form/View it is defined:

<span>Regular: </span> @Html.RadioButtonFor(model => model.EntryType, "RT", new { @ViewBag.RT })
<span> &nbsp;&nbsp; OverTime: </span> @Html.RadioButtonFor(model => model.EntryType, "OT", new { @ViewBag.OT })
<span> &nbsp;&nbsp; DoubleTime: </span> @Html.RadioButtonFor(model => model.EntryType, "DT", new { @ViewBag.DT })
<span> &nbsp;&nbsp; Free: </span> @Html.RadioButtonFor(model => model.EntryType, "0$", new { @ViewBag.ZT })

The "new ViewBag..." is not in the create part. In the Controller's Edit ActionResult I have:

ViewBag.RT = "";
ViewBag.OT = "";
ViewBag.DT = "";
ViewBag.ZT = "";
switch (timeEntryModel.EntryType)
{
            case "RT":
                ViewBag.RT = "@checked =  \"checked\"";
                break;
            case "OT":
                ViewBag.OT = "checked =  \"checked\"";
                break;
            case "DT":
                ViewBag.DT = "checked =  \"checked\"";
                break;
            case "ZT":
                ViewBag.ZT = "checked =  \"checked\"";
                break;
   }

This works, but is there a proper way to set the checked radio base on the value in the database or based on the value in a ViewBag entry?




Aucun commentaire:

Enregistrer un commentaire