Question

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
    }); 
Was it helpful?

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>
}

OTHER TIPS

i would create a custom html helper and make helper function to only return output when a criteria is met.

In the custom helper check if user is in role or authorized then return the html from custom html helper else return empty string.

Here is an example:

http://blogs.technet.com/b/sateesh-arveti/archive/2013/09/06/custom-html-helper-methods-in-asp-net-mvc-4.aspx

also look at this nice article:

http://www.codeproject.com/Articles/649394/ASP-NET-MVC-Custom-HTML-Helpers-Csharp

Hope it helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top