Saturday 30 July 2016

How to create navigation menu from database

1) Add a class named "CustomHHelpers" in your model folder.
namespace MvcApplication2.Models
{
    public static class CustomHHelpers
    {
        public static MvcHtmlString getTopMenu(this HtmlHelper htmlHelper,
  string url)
        {
            StringBuilder sbMenu = new StringBuilder();
            sbMenu.Append("<ul>");
            sbMenu.Append("<li><a href=\"" + url + "\">Home</a></li>");

            var menus = menuItems.insertDemoData();
            foreach (var m in menus)
            {
                sbMenu.Append("<li><a href=\"" + url + "\\" + m.url + "\">" 
 + m.urlName + "</a></li>");
            }
            //==== Close dynamic menu unordered list.
            sbMenu.Append(" <li><a href=\"#\">Contact Us</a></li>");
            sbMenu.Append("</ul>");
            return MvcHtmlString.Create(sbMenu.ToString());
        }
    }
    public class menuItems
    {
        public int Id { get; set; }
        public string urlName { get; set; }
        public string url { get; set; }

        public static List<menuItems> insertDemoData()
        {
            List<menuItems> obj = new List<menuItems>();
            obj.Add(new menuItems { Id = 1, 
urlName = "Anketler", url = "Anketler" });
            obj.Add(new menuItems { Id = 1, 
 urlName = "Duyurular", url = "Duyurular" });
            obj.Add(new menuItems { Id = 1, 
urlName = "Kullanıcı Profili", url = "Profil" });
            return obj;
        }
    }
}
 
 
 
2) Use in your _Layout.html or where you want to use:
@Html.getTopMenu(@Url.Content("~/"+@ViewContext.RouteData.Values["controller"].ToString()))
 

Tuesday 19 July 2016

Stored Procedure with both input and output parameters

Store Procedure
CREATE PROCEDURE [dbo].[GetPermission]
    @userName varchar(50),
    @permission int output
AS
BEGIN

    select @permission = PERMISSION from USERS where UserName = @userName

END;
EDIT:
another option is create a function instead, example:
CREATE FUNCTION [dbo].[GetPermission](@userName [varchar(50)])
RETURNS [int] 
AS 
BEGIN

    declare @permission int

    select @permission = PERMISSION from USERS where UserName = @userName

    return @permission

END;

Friday 15 July 2016

Update Pannel in MVC 3

In that case what I would do is to add a div with and id which will hold the new data, like: <div id="dataHolder"></div>
Your jQuery should look something like this:
$(function() {
    $("input[type='button']").click(function() { // if your button has an ID value use that instead, like $("#myId")
        $.get(yourUrl, function(data) {
                $("#dataHolder").html(data);
        }

        return false; // to prevent any default action
});
Ideally, your action should return a partial view (or JsonResult if you need to work with JSON data).
public ActionResult MyAction()
{
      // do something

      return PartialView("MyViewThatReturnsSomethingLikeTable", modelDataForMyPartialView);
}

Updating PartialView mvc 4



So, say you have your View with PartialView, which have to be updated by button click:
<div class="target">
    @{ Html.RenderAction("UpdatePoints");}
</div>

<input class="button" value="update" />
There are some ways to do it. For example you may use jQuery:
<script type="text/javascript">
    $(function(){   
        $('.button')click(function(){       
            $.post('@Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
                $('.traget').Load('/Home/UpdatePoints');       
            })       
        });
    });       
</script>
PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
[HttpPost]
public ActionResult UpdatePoints()
{   
    ViewBag.points =  _Repository.Points;
    return PartialView("UpdatePoints");

Updating PartialView mvc 4



So, say you have your View with PartialView, which have to be updated by button click:
<div class="target">
    @{ Html.RenderAction("UpdatePoints");}
</div>

<input class="button" value="update" />
There are some ways to do it. For example you may use jQuery:
<script type="text/javascript">
    $(function(){   
        $('.button')click(function(){       
            $.post('@Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
                $('.traget').Load('/Home/UpdatePoints');       
            })       
        });
    });       
</script>
PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
[HttpPost]
public ActionResult UpdatePoints()
{   
    ViewBag.points =  _Repository.Points;
    return PartialView("UpdatePoints");

Html submission by ValidateInput and AllowHtml attribute in MVC4

Sometimes, your required to save Html data in the database. By default Asp.Net MVC doesn't allow a user to submit html for avoiding Cross Site Scripting attack to your application. Suppose you have below form and you can submit the Html in description textarea.

If you do this and try to submit it you will get the error as shown in fig.

However, if you want to do this, you can achieve it by using ValidateInput attribute and AllowHtml attribute.

ValidateInput Attribute

This is the simple way to allow the submission of HTML. This attribute can enable or disable input validation at the controller level or at any action method.

ValidateInput at Controller Level

  1. [ValidateInput(false)]
  2. public class HomeController : Controller
  3. {
  4. public ActionResult AddArticle()
  5. {
  6. return View();
  7. }
  8. [HttpPost]
  9. public ActionResult AddArticle(BlogModel blog)
  10. {
  11. if (ModelState.IsValid)
  12. {
  13. }
  14. return View();
  15. }
  16. }
Now, the user can submit Html for this Controller successfully.

ValidateInput at Action Method Level

  1. public class HomeController : Controller
  2. {
  3. public ActionResult AddArticle()
  4. {
  5. return View();
  6. }
  7. [ValidateInput(false)]
  8. [HttpPost]
  9. public ActionResult AddArticle(BlogModel blog)
  10. {
  11. if (ModelState.IsValid)
  12. {
  13. }
  14. return View();
  15. }
  16. }
Now, the user can submit Html for this action method successfully.

Limitation of ValidateInput attribute

This attribute also has the issue since this allow the Html input for all the properties and that is unsafe. Since you have enable Html input for only one-two properties then how to do this. To allow Html input for a single property, you should use AllowHtml attribute.

AllowHtml Attribute

This is the best way to allow the submission of HTML for a particular property. This attribute will be added to the property of a model to bypass input validation for that property only. This explicit declaration is more secure than the ValidateInput attribute.
  1. using System.ComponentModel.DataAnnotations;
  2. using System.Web.Mvc; 
  3. public class BlogModel
  4. {
  5. [Required]
  6. [Display(Name = "Title")]
  7. public string Title { get; set; }
  8. [AllowHtml]
  9. [Required]
  10. [Display(Name = "Description")]
  11. public string Description{ get; set; }
  12. }
Make sure, you have removed the ValidateInput attribute from Conroller or Action method. Now, the user can submit Html only for the Description property successfully.

Html submission by ValidateInput and AllowHtml attribute in MVC4

Sometimes, your required to save Html data in the database. By default Asp.Net MVC doesn't allow a user to submit html for avoiding Cross Site Scripting attack to your application. Suppose you have below form and you can submit the Html in description textarea.

If you do this and try to submit it you will get the error as shown in fig.

However, if you want to do this, you can achieve it by using ValidateInput attribute and AllowHtml attribute.

ValidateInput Attribute

This is the simple way to allow the submission of HTML. This attribute can enable or disable input validation at the controller level or at any action method.

ValidateInput at Controller Level

  1. [ValidateInput(false)]
  2. public class HomeController : Controller
  3. {
  4. public ActionResult AddArticle()
  5. {
  6. return View();
  7. }
  8. [HttpPost]
  9. public ActionResult AddArticle(BlogModel blog)
  10. {
  11. if (ModelState.IsValid)
  12. {
  13. }
  14. return View();
  15. }
  16. }
Now, the user can submit Html for this Controller successfully.

ValidateInput at Action Method Level

  1. public class HomeController : Controller
  2. {
  3. public ActionResult AddArticle()
  4. {
  5. return View();
  6. }
  7. [ValidateInput(false)]
  8. [HttpPost]
  9. public ActionResult AddArticle(BlogModel blog)
  10. {
  11. if (ModelState.IsValid)
  12. {
  13. }
  14. return View();
  15. }
  16. }
Now, the user can submit Html for this action method successfully.

Limitation of ValidateInput attribute

This attribute also has the issue since this allow the Html input for all the properties and that is unsafe. Since you have enable Html input for only one-two properties then how to do this. To allow Html input for a single property, you should use AllowHtml attribute.

AllowHtml Attribute

This is the best way to allow the submission of HTML for a particular property. This attribute will be added to the property of a model to bypass input validation for that property only. This explicit declaration is more secure than the ValidateInput attribute.
  1. using System.ComponentModel.DataAnnotations;
  2. using System.Web.Mvc;
  3.  
  4. public class BlogModel
  5. {
  6. [Required]
  7. [Display(Name = "Title")]
  8. public string Title { get; set; }
  9.  
  10. [AllowHtml]
  11. [Required]
  12. [Display(Name = "Description")]
  13. public string Description{ get; set; }
  14. }
Make sure, you have removed the ValidateInput attribute from Conroller or Action method. Now, the user can submit Html only for the Description property successfully.