I have a model like this
public class Roles
{
[Key]
public string RoleId {get;set;}
public string RoleName {get;set;}
}
The challenge I have with this is creating a single view for the List and create. Each attempt I have made ended up in data type error. What do I do?
Answer 1:
In Order to hide some fields(as asked in Comments section) in @Html.EditorForModel()
you have to use :
[ScaffoldColumn(false)]
attribute
Ex :-
[Key]
[ScaffoldColumn(false)]
public string RoleId {get;set;}
Answer 2:
and creating and showing list on the same view :
Model :
public class Roles
{
[Key]
public string RoleId {get;set;}
public string RoleName {get;set;}
public List<Roles> Roleslist { get;set; } //Take a list in Model as shown
}
View :
<div id="mainwrapper">
@using (Html.BeginForm("// Action Name //", "// Controller Name //", FormMethod.Post, new { @id = "form1" }))
{
@Html.TextBoxFor(m => m.RoleName)
<input type="submit" value="Save"/>
}
<div id="RolesList">
@if(Model!=null)
{
if(Model.Roleslist!=null)
{
foreach(var item in Model.Roleslist) //Just Populate Roleslist with values on controller side
{
//here item will have your values of RoleId and RoleName
}
}
}
</div>
</div>