I have an ASP.NET MVC5 web app. Users can add projects (database entries) and the project also stores the userId of the user that adds a project. I've added the restriction in the controller that won't let other users from deleting or editing your entries, only if it is you.
Here is how it looks in the controller:
public ActionResult Edit([Bind(Include = "ProjectId,UserId,Title,ApplicationDeadline,Duration,HourlyRate,TotalProjectCost,City,RequiredPresencePercent,Language,RequiredSkills,Description")] Project project)
{
if (ModelState.IsValid)
{
if (project.UserId == User.Identity.GetUserId())
{
db.Entry(project).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return HttpNotFound("Project is not yours!");
}
return View(project);
}
but in the View there still is an actionlink
@Html.ActionLink("Edit", "Edit", new {id = item.ProjectId})
How can I add a check inside this .cshtml file so the Edit/Delete actionlinks don't even appear near the projects that are not yours?
I've tried @if (project.UserId == User.Identity.GetUserId())
but of course, project
is not defined here.
EDIT: Found the solution thanks to Stephen
@if(item.UserId == User.Identity.GetUserId())
{
@Html.ActionLink("Edit", "Edit", new {id = item.ProjectId})
@Html.ActionLink("Delete", "Delete", new {id = item.ProjectId})
}
使用Model.project之类的
@if(Model.project)
You can use this:
@if(Model.project.UserId == User.Identity.GetUserId()) {
Html.ActionLink("Edit", "Edit", new {id = item.ProjectId})
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.