I've made a Profile Model
that stores certain property values. Such as firstName, lastName... etc... Among others state
is one of them.
Now problem occurred when I've replaced TextBox
with DropDownList
for State
property.
This is the way I've made my Edit
method in ProfileController
.
When opened app will populate if any existing values. First issue, how to get selected value from the dropdown, so i can pass it into Profile
property like I did in this method.
public ActionResult Edit(string username)
{
ViewBag.StateID = new SelectList(db.States, "StateID", "StateName");
ProfileBase _userProfile = ProfileBase.Create(username);
ProfileModel _profile = new ProfileModel();
System.Web.HttpContext.Current.Session["_userName"] = username;
if (_userProfile.LastUpdatedDate > DateTime.MinValue)
{
_profile.FirstName = Convert.ToString(_userProfile.GetPropertyValue("FirstName"));
_profile.LastName = Convert.ToString(_userProfile.GetPropertyValue("LastName"));
_profile.Address = Convert.ToString(_userProfile.GetPropertyValue("Address"));
_profile.City = Convert.ToString(_userProfile.GetPropertyValue("City"));
_profile.State = Convert.ToString(_userProfile.GetPropertyValue("State"));
_profile.Zip = Convert.ToString(_userProfile.GetPropertyValue("Zip"));
}
return View(_profile);
}
This worked fine when State
was a string passed in TextBox
, and then saved with Edit
post method.
[HttpPost]
public ActionResult Edit(ProfileModel model)
{
if (ModelState.IsValid)
{
ProfileBase profile = ProfileBase.Create(System.Web.HttpContext.Current.Session["_userName"].ToString(), true);
if (profile != null)
{
profile.SetPropertyValue("FirstName", model.FirstName);
profile.SetPropertyValue("LastName", model.LastName);
profile.SetPropertyValue("Address", model.Address);
profile.SetPropertyValue("City", model.City);
profile.SetPropertyValue("State", model.State);
profile.SetPropertyValue("Zip", model.Zip);
profile.Save();
}
else
{
ModelState.AddModelError("", "Error writing to Profile");
}
}
return RedirectToAction("Index");
}
This is how I created dropdown for State
.
Model:
public class State
{
public int StateID { get; set; }
public string StateName { get; set; }
public IEnumerable<RegisterModel> RegModel { get; set; }
public IEnumerable<ProfileModel> Profiles { get; set; }
}
Controller:
ViewBag.StateID = new SelectList(db.States, "StateID", "StateName");
View:
@Html.DropDownList("StateID", (SelectList)ViewBag.StateID, new { @class = "dropdown" })
I've tried several things. No luck so far. What am I missing?!