开发者

Dynamic button .net MVC

开发者 https://www.devze.com 2023-01-31 10:19 出处:网络
I wish to create a follow style button on a view in MVC but not sure whether I should be using a HTMLHelper to do this 开发者_高级运维or not.

I wish to create a follow style button on a view in MVC but not sure whether I should be using a HTMLHelper to do this 开发者_高级运维or not. The button will obviously need to show different text depending upon whether or not the user is already following the item and call a different script when clicked if the user is deciding to follow or unfollow.

Should the helper create the button entirely or just the contents of the button?


MVC purists would argue that the decision on whether the user can follow the item should be made in the controller and passed in the Model. That boolean value would then be passed to the HTMLHelper.

public static string FollowButton(this HtmlHelper source, bool isFollowing) {
  if (isFollowing) {
    return "<button>Unfollow</button>  //unfollow button
  }
  else {
    return "<button>Follow</button>  //follow button
  }
}

Then on your view

<%= Html.FollowButton(Model.IsUserFollowing) %>

And following standards, your JavaScript should be created separately. You could use class="follow" on your follow button as a means for your JavaScript to identify which script should be used.


If the helper will always be used for the button text and nowhere else, then I'd just put the entire button inside the helper to simplify your code.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号