i want to create users with special features in mvc. when user is going to create i want to assign some special feature to each user like particular user having his own house, h
Use view models to represent what you display and edit
public class FeatureVM
{
public int ID { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class UserVM
{
public string Name { get; set; }
public string Address { get; set; }
public List<FeatureVM> Features { get; set; }
}
Controller
public ActionResult Create()
{
UserVM model = new UserVM();
model.Features = // map all available features
return View(model);
}
[HttpPost]
public ActionResult Create(UserVM model)
{
}
View
@model UserVM
@using(Html.BeginForm())
{
@Html.LabelFor(m => m.Name)
@Html.TextBoxFor(m => m.Name)
@Html.ValidationMessageFor(m => m.Name)
.....
for(int i = 0; i < Model.Features.Count; i++)
{
@Html.HiddenFor(m => m.Features[i].ID)
@Html.CheckBoxFor(m => m.Features[i].IsSelected)
@Html.LabelFor(m => m.Features[i].IsSelected, Model.Features[i].Name)
}
<input type="submit" value="Create" />
}
try with this, in you Model of Feature add a new property
public bool isFeatureOf { get; set; }
also in your model for the method AddNewUser change it to
public void AddNewUser(User userAdd,List<Feature> features)
{
userService = new UserService(userDbContext);
User = userService.AddUser(userAdd);
userService.SaveUser();
//featureService = new FeatureService(yourdbcontext)
foreach (Feature item in features)
{
//save to db
featureService.SaveFeature(item,User.Id);
//i don't know if in your database you already have a table,colum or something to map the features by user
}
}
then in your view
for(int index=0; index < Model.Features.Count(); index++)
{
@Html.HiddenFor(m=>Model.Features[index].NameFeature)
@Html.Raw(Model.Features[index].NameFeature)
@Html.CheckBoxFor(m=>Model.Features[index].isFeatureOf)
}
also in your view you'll need to change this
<div>
@Html.TextBoxFor(m => m.User.UserName)
@Html.ValidationMessageFor(m => m.UserName)
</div>
<div>
@Html.TextBoxFor(m => m.User.UserAddres)
@Html.ValidationMessageFor(m => m.UserAddres)
</div>
to:
<div>
@Html.TextBoxFor(m =>Model.User.UserName)
@Html.ValidationMessageFor(m => Model.User.UserName)
</div>
<div>
@Html.TextBoxFor(m => m.User.UserAddres)
@Html.ValidationMessageFor(m =>Model.User.UserAddres)
</div>
in your controller change your param to get the whole Model like this
[HttpPost]
public ActionResult Create(ViewModelUserWithFeature model)
{
if (ModelState.IsValid)
{
model.AddNewUser(model.User,model.Features);
}
return RedirectToAction("Index", viewModelUserWithFeature);
}
hope this can help you