Thursday 26 May 2016

MVC - Fix error The name 'Path' does not exist in the current context

Watch this example on YouTube:
to fix it replace 
        public ActionResult ImportFile(HttpPostedFileBase file)
        {
            if (Request.Files.Count > 0)
            {
                var fil = Request.Files[0];
                if (fil != null && fil.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
                    file.SaveAs(path);
                }
            }
            return View();
with
        public ActionResult ImportFile(HttpPostedFileBase file)
        {
            if (Request.Files.Count > 0)
            {
                var fil = Request.Files[0];
                if (fil != null && fil.ContentLength > 0)
                {
                    var fileName = System.IO.Path.GetFileName(file.FileName);
                    var path = System.IO.Path.Combine(Server.MapPath("~/Images/"), fileName);
                    file.SaveAs(path);
                }
            }
            return View();

Saturday 21 May 2016

MVC - Fix the following error - The type or namespace name 'SelectListItem' could not be found (are you missing a using directive or an assembly reference?)


Watch this example on YouTube:
Error while executing the following code:
        public IEnumerable<SelectListItem> Months
        {
            get
            {
                return DateTimeFormatInfo
                       .InvariantInfo
                       .MonthNames
                       .Select((monthName, index) => new SelectListItem
                       {
                           Value = (index + 1).ToString(),
                           Text = monthName
                       });
            }
        }

To fix it add the following using:
using System.Globalization;

MVC - Fix the following error - Error The name 'DateTimeFormatInfo' does not exist in the current context

Watch this on YouTube:
error while executing the following code:
public IEnumerable<SelectListItem> Months
        {
            get
            {
                return DateTimeFormatInfo
                       .InvariantInfo
                       .MonthNames
                       .Select((monthName, index) => new SelectListItem
                       {
                           Value = (index + 1).ToString(),
                           Text = monthName
                       });
            }
        }
To fix it - add the following using:
using System.Globalization;

Wednesday 18 May 2016

MVC - Sorting Paging Filtering using ViewModel (not ViewBag)

watch this example on YouTube


SortAndPage class
namespace MvcSortAndFilterAndPage.Models
{
    public class SortAndPage
    {
        public string SortField { get; set; }
        public string SortDirection { get; set; }
        public int PageSize { get; set; }
        public int PageCount { get; set; }
        public int CurrentPageIndex { get; set; }
    }
}
Customer Custom class
namespace MvcSortAndFilterAndPage.Models
{
    public class CustomerCustom :SortAndPage
    {
        public IEnumerable<Customers2> cust { get; set; }
        public IEnumerable<Customers2> custDDL { get; set; }
        public string SelectedFirstName { get; set; }
        public string SelectedLastName { get; set; }
    }
}

add the following to _layout.cshtml 
        @Scripts.Render("~/Scripts/jquery-1.8.2.min.js")
        @Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.js")
    </head>

Here is modified part of CustomerController
using MvcSortAndFilterAndPage.Models;

namespace MvcSortAndFilterAndPage.Controllers
{
    public class CustomerController : Controller
    {
        private TESTEntities db = new TESTEntities();

        //
        // GET: /Customer/

        public ActionResult Index(CustomerCustom model = null)
        {
            int i;
            if (model != null)
            {
                i = model.CurrentPageIndex;
            }
            model = new CustomerCustom
            {
                cust = db.Customers2.ToList(),
                custDDL = db.Customers2.ToList()
            };
            var res = (from s in model.cust
                       select s);
            res = res.ToList();
            if (model.CurrentPageIndex == 0)
            {
                model.CurrentPageIndex = 0;
            }
            model.PageSize = 2;
            model.PageCount = ((res.Count() + model.PageSize - 1) / model.PageSize);
            if (model.CurrentPageIndex > model.PageCount)
            {
                model.CurrentPageIndex = model.PageCount;
            }
            model.cust = res.Skip(model.CurrentPageIndex * model.PageSize).Take(model.PageSize);



            return View(model);
        }

        [HttpPost]
        public ActionResult Index(CustomerCustom model, string btn = null){
            if (model.SortField == null){
                model.SortField = "CustomerFirstName";
                model.SortDirection = "ascending";
            }
            #region SortData

            switch(model.SortField){
                case "CustomerFirstName":
                    model.cust = (model.SortDirection == "ascending" ?
                        db.Customers2.OrderBy(c => c.CustomerFirstName):
                        db.Customers2.OrderByDescending(c => c.CustomerFirstName));
                    break;
                case "CustomerLastName":
                    model.cust = (model.SortDirection == "ascending" ?
                        db.Customers2.OrderBy(c => c.CustomerLastName):
                        db.Customers2.OrderByDescending(c => c.CustomerLastName));
                    break;
            }
               
            #endregion

            var ddl = (from d in model.cust
                       select d);
            model.custDDL = ddl;

            #region FilterData

            if (!String.IsNullOrEmpty(model.SelectedFirstName))
            {
                model.cust = model.cust.Where(s => s.CustomerFirstName.ToString().Trim().Equals(model.SelectedFirstName.Trim()));
            }
            if(!String.IsNullOrEmpty(model.SelectedLastName))
            {
                model.cust = model.cust.Where(s => s.CustomerLastName.ToString().Trim().Equals(model.SelectedLastName.Trim()));
            }

            #endregion

            var res = (from s in model.cust
                           select s);
            res = res.ToList();
            if(model.CurrentPageIndex == 0){
                model.CurrentPageIndex = 0;
            }
            model.PageSize =2;
            model.PageCount = ((res.Count() + model.PageSize - 1) / model.PageSize);
            if(model.CurrentPageIndex > model.PageCount){
                model.CurrentPageIndex = model.PageCount;
            }
            model.cust = res.Skip(model.CurrentPageIndex * model.PageSize).Take(model.PageSize);
            return View(model);
        }
View(Index.cshtml) will look like this:
@model MvcSortAndFilterAndPage.Models.CustomerCustom

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>

@using (Html.BeginForm(null, null, FormMethod.Post))
{
    @Html.AntiForgeryToken()
    @Html.Hidden("SortField", Model.SortField)
    @Html.Hidden("SortDirection", Model.SortDirection)
    @Html.Hidden("PageCount", Model.PageCount)
    @Html.Hidden("PageSize", Model.PageSize)
    @Html.Hidden("CurrentPageIndex", Model.CurrentPageIndex)
   
    @Html.Hidden("SelectedFirstName", Model.SelectedFirstName)
    @Html.Hidden("SelectedLastName", Model.SelectedLastName)


<table>
    <tr>
        <th>
            <a href="#" data-sortfield="CustomerFirstName" class="header">@Html.DisplayNameFor(model => model.cust.First().CustomerFirstName)</a>
        </th>
        <th>
            <a href="#" data-sortfield="CustomerLastName" class="header">@Html.DisplayNameFor(model => model.cust.First().CustomerLastName)</a>
        </th>
        <th></th>
    </tr>
    <tr>
        <th>
            @Html.DropDownListFor(model => model.SelectedFirstName,
            new SelectList(Model.custDDL, "CustomerFirstName", "CustomerFirstName", Model.SelectedFirstName), "All", new  {@id = "fn" })
        </th>
        <th>
            @Html.DropDownListFor(model => model.SelectedLastName,
            new SelectList(Model.custDDL, "CustomerLastName", "CustomerFirstName", Model.SelectedLastName), "All", new { @id = "ln" })
        </th>

    </tr>

@foreach (var item in Model.cust) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.CustomerFirstName)
        </td>
        <td>
            @Html.DisplayFor(modelItem => item.CustomerLastName)
        </td>
        <td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}

    <tr>
        <td colspan="4">
            @for (var i = 0; i < Model.PageCount; i++)
            {
                if (i == Model.CurrentPageIndex)
                {
                    <span class="current-pager" id="CurrentPageIndex">@(i + 1)</span>
                }
                else
                {
                    <a href="#" data-pageindex="@i" class="pager">@(i + 1)</a>
                }
            }
        </td>
    </tr>

</table>
   
}
<script type="text/javascript">
    $(document).ready(function () {
        $(".header").click(function (evt) {       
            var sortfield = $(evt.target).data("sortfield");
            if ($("#SortField").val() == sortfield) {
                if ($("#SortDirection").val() == "ascending") {
                    $("#SortDirection").val("descending");
                }
                else{
                    $("#SortDirection").val("ascending");
                }
            }
            else {
                $("#SortField").val(sortfield);
                $("#SortDirection").val("ascending");
            }
            evt.preventDefault();
            $("form").submit();
           
        });

        $(".pager").click(function (evt) {
            var pageindex = $(evt.target).data("pageindex");
            $("#CurrentPageIndex").val(pageindex);
            evt.preventDefault();
            $("form").submit();
        });

        $("#fn").change(function (evt) {
            $("#SelectedFirstName").val($("#fn").val().trim());
            evt.preventDefault();
            $("form").submit();
        })
        $("#ln").change(function (evt) {
            $("#SelectedLastName").val($("#ln").val().trim());
            evt.preventDefault();
            $("form").submit();
        })
    });
</script>

Thursday 12 May 2016

C# - LINQ to List - Group and Count


Watch this example on YouTube

    public class test
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public partial class LINQ_List_Group_Count_test : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            List<test> myList = new List<test>(){
                new test(){Name ="Frank", Age =80},
                new test(){Name = "Bob", Age = 30},
                new test(){Name = "Bob", Age = 50},
                new test(){Name = "John", Age = 40}
            };
            var AllNames = from m in myList select m.Name;
            var UniqueNames = from a in myList
                              group a by a.Name into g
                              select g.Count();
            Response.Write(UniqueNames.Count().ToString());
            Response.Write("<br />");
            Response.Write(AllNames.Count().ToString());
           
        }

ASP.NET - Input type file - set width by ID in CSS


Watch this example on YouTube
    <div>
        <input type="file" id="ImportFile" />
    </div>


CSS
#ImportFile{
    width: 50em;
}

Wednesday 11 May 2016

C# - ASP.NET - String - get first character (letter) of a string


WATCH THIS EXAMPLE ON YOUTUBE

            string test = "ABCDEFG";
            Response.Write(test.Substring(0, 1));

Tuesday 10 May 2016

C# - ASP.NET - String - get text before and after specified character (space)

Watch this example on YouTube

       string test = "one two";
            string s1 = test.Substring(0, test.IndexOf(" "));
            string s2 = test.Substring(test.IndexOf(" ") + 1);
            Response.Write(s1);
            Response.Write("<br />");
            Response.Write(s2);

Saturday 7 May 2016

MVC - jQuery - Add new item to dropdownlist (select list)




Watch this example on youtube


<h2>AddItemsToDDL</h2>
<select id="Select1">
    <option value="1">Blue</option>
    <option value="2">Yellow</option>

</select>

<script type="text/javascript">
    $(document).ready(function () {
        var NewOption = "<option value='" + "3" + "'>Gold</option>";
        $("#Select1").append(NewOption);
    });
</script>

MSSQL - Get list of all error messages

Watch this example on YouTube

select * from sys.messages

Thursday 5 May 2016

MVC - jQuery - check if checkbox is checked (selected)

Watch this example on YouTube:

<input id="Checkbox1" type="checkbox" />

<script type="text/javascript">
    $('#Checkbox1').attr('checked', true);

    if ($('#Checkbox1').is(':checked')) {
        alert('checked!!!');
    }

</script>

MVC - jQuery - Check (select) checkbox


Watch this example on YouTube

<input id="Checkbox1" type="checkbox" />

<script type="text/javascript">
    $('#Checkbox1').attr('checked', true);
</script>