Search code examples
c#asp.netasp.net-mvc-4social-networking

How to show a specific html elements for specific authorized users in ASP.NET MVC 4


I am building very very simple soical network and here is my question: For example I want to show a button "Change profile picture" on user's page only for user which owns this profile and should be hidden for other authorized users. Any suggestions?

Here is my Login method:

[HttpPost]
        public ActionResult Login(LoginModel user)
        {
            if (ModelState.IsValid)
            {
                if (IsValid(user.UserName, user.Password))
                {
                    FormsAuthentication.SetAuthCookie(user.UserName, false);
                    return RedirectToAction("About", "User", new{ username = user.UserName });
                }
                else
                {
                    ModelState.AddModelError("", "Login data is incorrect");
                }
            }
            return View(user);
        }

LoginModel:
    public class LoginModel
    {
        [Required]
        [DataType(DataType.Password)]
        [StringLength(20, MinimumLength = 6)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [Required]
        [DataType(DataType.Text)]
        [StringLength(100)]
        [Display(Name = "User name")]
        public string UserName { get; set; }
    }

And the route for user profiles:

routes.MapRoute(
    name: "User",
    url: "{UserName}",
    defaults: new
    {
        controller = "User",
        action = "About",
        id = UrlParameter.Optional
    }); 

Solution

  • You can simply set a variable from the Model in the Controller indicating that you want to show a particular part of the html.

    Sample:

    In your model add a property:

    public TestModel
    {
        public bool ShowContentX {get;set;}
    }
    

    In your Controller, fill it and pass the model to the View:

    TestModel t = new TestModel();
    t.ShowContentX = true; // create check here.
    
    return View(t);
    

    In your View, check if the property is true:

    @if (@model.ShowContentX) {
      <p>add your html</p>
    }