Reputation: 233
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?
Upvotes: 2
Views: 6906
Reputation: 803
Also check your controller to ensure you are not passing Roles.ToList()
to the CreateRole
view.
You can do this:
[HttpGet]
public ActionResult CreateRole()
{
var roles = from ur in db.roles
orderby ur.RoleName
select ur;
ViewBag.Listroles = roles.ToList();
return View();
}
where db
is your DbContext
.
And your view should look like this:
@{
if(ViewBag.Listroles != null){
foreach (var roles in ViewBag.Listroles)
{
<tr>
<td>@roles.RoleName</td>
<td>
@Html.ActionLink("Edit", "EditRoles", new { id=roles.RoleId }) |
@Html.ActionLink("Details", "Details", new { id=roles.RoleId }) |
@Html.ActionLink("Delete", "Delete", new { id=roles.RoleId })
</td>
</tr>
}
}
}
Let me know if my answer helps.
Upvotes: 2
Reputation: 18873
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>
Upvotes: 2