I'm learning ASP.Net web pages programming using Webmatrix (with razor syntax).
Goal is to have dropdown list boxes populated by values stored in a table and the selected value coming from another joined table.
The selected value should be shown before and after a post.
I also want that if there is no UserTypeId in the UserProfiles table (UserTypeId == NULL), a default "Please select" would be shown.
Table 1: UserTypes with UserTypeId and Name fields Table 2: UserProfiles with UsertypeId as foreign key
I have the following error message and don't find how to solve that issue: Operator '==' cannot be applied to operands of type 'int' and 'WebMatrix.Data.DynamicRecord'
CODE section:
var db = Database.Open("MyDatabase");
To get the UserTypeId stored in the UserProfiles table for the connected user
var selectedUserTypeId = db.QuerySingle("SELECT UserTypeId FROM UserProfiles INNER JOIN Users ON UserName=@0",authenticatedUser);
To get the list of the UserTypes
var sqlUserTypeData = "SELECT userTypeId, Name FROM UserTypes";
var userTypeData = db.Query(sqlUserTypeData);
var userTypeDataList = userTypeData.Select(userTypeDataListItem => new SelectListItem {
Value = userTypeDataListItem.UserTypeId.ToString(),
Text = userTypeDataListItem.Name,
Selected = userTypeDataListItem.UserTypeId == selectedUserTypeId ? true : false
});
Last line is where the issue occurs: userTypeDataListItem.UserTypeId == selectedUserTypeId. These types cannot apparently be compared.
if(!IsPost){
var sqlUserData = @"SELECT *, UserTypes.Name AS UserType
FROM UserProfiles
INNER JOIN Users ON Users.UserId = UserProfiles.UserId
INNER JOIN UserTypes ON UserTypes.UserTypeId = UserProfiles.UserTypeId
WHERE Users.UserName=@0";
var userData = db.QuerySingle(sqlUserData,authenticatedUser);
userType = userData.UserType;
}
if(IsPost){
Validation.RequireField("userTypeCombo", "Please select");
userId = Request.Form["userId"];
userTypeId = Request.Form["userTypeCombo"];
if(Validation.IsValid()) {
var updateCommand = @"UPDATE UserProfiles
SET UserTypeId=@0
WHERE UserId=@1";
db.Execute(updateCommand, userTypeId, userId);
Response.Redirect("~/authcontent/user");
}
HTML section:
@if (isAuthenticated) {
<form action="" method="post">
@Html.ValidationSummary()
<section class="infoblock">
<fieldset>
<legend>Mon profil</legend>
<ul>
<li><label for="userType">Profil</label>
@Html.DropDownList("userTypeCombo", "Please select", userTypeDataList)</li>
</ul>
</fieldset>
</section>
</form>
}