TAGS :Viewed: 18 - Published at: a few seconds ago

[ Get back @html.dropdownlist ID value for database insert / update in Webmatrix ]

I have build some dropdown lists using the LINK to Objects method and @html.dropdownlist Webmatrix helper. This works fine.

I want to know how to pass / store the selected value in my database table.

Build of items list in code section

var titlesData = db.Query("SELECT TitleId, Name FROM Titles ORDER BY Name");
        titlesListItems = titlesData.Select(i => new SelectListItem {
        Value = i.TitleId.ToString(),
        Text = i.Name,
        Selected = i.TitleId == providerData.TitleId ? true : false
        });

HTML markup section:

@Html.DropDownList("titlesCombo","-- Veuillez sélectionner -- ",titlesListItems)

Database update command (see the ???):

db.Execute("UPDATE Providers SET TitleId=@0 WHERE ProviderId=@1",???,providerId)

The method I used for now is to create another variable:

var titleId = "";

if (!IsPost) {

    titleId = providerData.TitleId.ToString(); //providerData stores the SQL query result
}

if (IsPost) {

    var titleId = Request.Form[TitleID]
    db.Execute("UPDATE Providers SET TitleId=@0 WHERE ProviderId=@1",titleId,providerId)
}

Unfortunately, data doesn't get updated

Answer 1


From what I can see, you haven't referenced rightly the DropDownList helper in your code. Try with the following code:

var titleId = ""; 

if (!IsPost) { 
    titleId = providerData.TitleId.ToString();
} 

if (IsPost) { 
    titleId = Request.Form["titlesCombo"];
    db.Execute("UPDATE Providers SET TitleId=@0 WHERE ProviderId=@1",titleId,providerId);
}