Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
I am using asp.net mvc with code first entity framework. The dropdownlist saves selected value to the database, but when I go back to the page it just shows the select list values from the model.

What I have tried:

Model
------------
public class myRating
   {
       public int fRatingId { get; set; }
       public string Desc { get; set; }

       public IEnumerable<SelectListItem> listRatings { get; set; }
   }


Controller
----------------
public List<SelectListItem> GetRatingList()
        {
            var ratingList = db.fRatings.ToList()
                .Select(d => new SelectListItem
                {
                    Value = d.fRatingId.ToString(),
                    Text = d.Desc
                });
            return ratingList.ToList();

        }


model.listRatings = GetRatingList();


View
--------------
@foreach (var item in Model.myDpExercises)
<tr>
    <td>
        @Html.DisplayFor(modelitem => item.Exercise)
    </td>
       <td>

                        @Html.DropDownListFor(modelItem => item.RatingId,Model.listRatings, "--Please Select--", new { id = "ddlRating", onchange = "UpdateRating(this)", data_mydpexid = item.Id })
                        
                    </td>
</tr>
Posted
Updated 16-Oct-19 2:21am
Comments
Richard Deeming 14-Oct-19 14:17pm    
Is the problem that the "--Please Select--" option is always selected? That would be because you've not set the Selected property on any of the SelectListItem items.

But it's not clear from your code how you would know which item to select.

1 solution

Though your question is not pretty clear what's the problem What I understood from
when I go back to the page it just shows the select list values from the model.

is you're not redirecting after a successful post back to database, so you want to insert another record at the same view. MVC usually Maintain Model state of selected data and if you want to clear the form after a successful post back then you can Clear model state.
e.g.
C#
[HttpPost]
public ActionResult Create(CreateRequest request)
{
    var vm = new CrateViewMModel();

    if (ModelState.IsValid && Save to db was success)
    {
        vm.ResultMessage = "Success";

        return View("Create",vm);
    }

    ModelState.Clear(); // add this if you want to clear for all controls
    ModelState.Remove("IsActive"); // if just want to clear one control

    return View(vm);
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900