Translate

Tuesday, 21 April 2015

Cascading Dropdown List in asp.net MVC


In controller

   public ActionResult CascadingDropdown()
        {
            //Country count=new Country();
            ViewData["country"] = GetCountry();
            return View();

        }

In view

@model JQGridExample.Models.Country

@{
    ViewBag.Title = "CustomerFeedback";
}
<h2>CustomerFeedback</h2>
<link href="~/Content/css/Style.css" rel="stylesheet" />
<script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#Country").change(function () {
            $("#State").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetStates")',
                dataType: 'json',
                data: { id: $("#Country").val() },
                success: function (states) {
                 
                    $.each(states, function (i, state) {
                        $("#State").append('<option value="' + state.Value + '">' + state.Text + '</option>');
                    });
                },
                error: function (ex) {
                    alert('Failed to retrieve states.' + ex);
                }
            });
            return false;
        })
        $("#State").change(function () {
            $("#city").empty();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("GetCity")',
                dataType: 'json',
                data: { id: $("#State").val() },
                success: function (citys) {
                    $.each(citys, function (i, city) {
                        $("#city").append('<option value="'+ city.Value + '">' + city.Text + '</option>');
                    });
                },
                error: function (ex) {
                    alert('Failed to retrieve states.' + ex);
                }
            });
             return false;
         })

    });
</script>

@using (Html.BeginForm())
{
    <div class="editor-label">
        <br />
        <div style="color: Purple;">
            @Html.Label("Select County")
        </div>
        <div class="editor-field">
          
                @Html.DropDownListFor(m=>m.CountryName, new SelectList((System.Collections.IEnumerable)ViewData["country"],"value","text"),"Select",new { style = "width:250px", @class = "dropdown1",@id="Country" })
          
        </div>
        <br />
        <div style="color: Purple;">
            @Html.Label("Select State", new { style = "width:250px" })
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(m=>m.Statename, new SelectList(string.Empty, "Value", "Text"), "Please select a State", new { style = "width:250px", @class = "dropdown1",@id="State" })
        </div>
        <br />
        <div style="color: Purple;">
            @Html.Label("Select City", new { style = "width:250px" })
        </div>
        <div class="editor-field">
            @Html.DropDownListFor(m=>m.Cityname, new SelectList(string.Empty, "Value", "Text"), "Please select a city", new { style = "width:250px", @class = "dropdown1",@id="city" })
        </div>
        <div>
        <p class="mag">
            hello</p>
        <input type="text" class="mag">
    </div>
        <br />
        <input id="Submit1" type="submit" value="submit" />
    </div>
   
}

 In controller

  public List<Country> GetState(string id)
        {
            List<Country> lst = new List<Country>();
            Country country = null;
            int ids = Convert.ToInt32(id);
            var coun = systest.States.Where(u => u.CountryId == ids).ToList();
            for (int i = 0; i < coun.Count(); i++)
            {
                country = new Country();
                country.value = coun[i].StateId;
                country.Text = coun[i].StateName;
                lst.Add(country);
            }
            return lst;
        }

        public List<Country> GetCitys(string id)
        {
            List<Country> lst = new List<Country>();
            Country country = null;
            int idss = Convert.ToInt32(id);
            var coun = systest.Cities.Where(u => u.StateId == idss).ToList();
            for (int i = 0; i < coun.Count(); i++)
            {
                country = new Country();
                country.value = coun[i].Cityid;
                country.Text = coun[i].CityName;
                lst.Add(country);
            }
            return lst;
        }
        public JsonResult GetStates(string id)
        {

            Country count = new Country();
            List<Country> ListState = new List<Country>();
            ListState = GetState(id);
            return Json(new SelectList(ListState, "Value", "Text"));
        }

        public JsonResult GetCity(string id)
        {

            Country count = new Country();
            List<Country> ListCity = new List<Country>();
            ListCity = GetCitys(id);
            return Json(new SelectList(ListCity, "Value", "Text"));
        }

        [HttpPost]
        public ActionResult CascadingDropdown(FormCollection FC)
        {

            string country = FC["CountryName"].ToString();
            string state = FC["Statename"].ToString();
            string city = FC["Cityname"].ToString();
            ViewData["country"] = GetCountry();
            return View();
        }

 the Output like below



Auto complete textbox In mvc asp.net

       public ActionResult Auto()
        {
            return View();

        }


IN view

<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.11/jquery-ui.min.js"
    type="text/javascript"></script>
<script>
    $(document).ready(function () {
        $("#user").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '@Url.Action("Autocomplete", "JqGrid")', type: "POST", dataType: "json",
                    data: { query: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.UserName, value: item.UserName };
                        }))
                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        });
    });
</script>

In controller

public ActionResult Autocomplete(string query)
        {
var users = context.UserInfoes.Where(u =>  u.UserName.Contains(query)).ToList();
            return Json(users);
        }


The result Below




How to upload files in Mvc Application

  File Upload in mvc using C#


In controller you  have to write like below

     
    public ActionResult Fileup()
        {
            Sample smp = new Sample();
            smp.images = Listemp();
            return View(smp);
        }


Add  View to above ActionResult. and the View like below


@using (Html.BeginForm("Fileup", "JqGrid", FormMethod.Post, new { enctype    = "multipart/form-data" }))
{
    <input type="file" name="file" id="fup" />

    <input type="submit" id="btnSubmit" value="submit" />
}



Jquery validations for file upload write it in same view

<script src="~/Scripts/jquery-1.7.1.min.js"></script>

     <script type="text/javascript">
    $(function () {
        $('#btnSubmit').click(function () {
            // alternate
            var fileUpload1 = $("#fup").val();
            var extension1 =      fileUpload1.substring(fileUpload1.lastIndexOf('.'));


            var ValidFileType = ".doc , .pdf , .xls , .xlsx, .docx, .jpeg, .jpg, .png";
            var id = document.getElementById("fup").value;
            if (id.length > 0) {
                var extension = id.substring(id.lastIndexOf('.'));
                var fsize = $("#fup")[0].files[0].size;
                if (ValidFileType.toLowerCase().indexOf(extension) < 0) {
                    alert("Only doc,pdf,jpeg and xls files allowed.");
                    return false;
                }
                else if (parseInt(fsize) > parseInt(1024 * 1024 * 3)) {
                    alert('File size must 3 MB or below.');
                    return false;
                }
            }
            else {
                alert('Please select File.');
                return false;
            }
        });
    });
</script>

 the view show like below




Post method to save selected file 


       [HttpPost]
        public ActionResult Fileup(HttpPostedFileBase file, FormCollection fc)
        {
            Sample smp = new Sample();
            if (file != null && file.ContentLength > 0)
                try
                {
             string path =      Path.Combine(Server.MapPath("~/Images//Upload"),   Path.GetFileName(file.FileName));
                    if (System.IO.File.Exists(path))
                    {
                    }
                    file.SaveAs(path);
                    TempData["Success"] = "File uploaded successfully";
                    smp.images = Listemp();
                }
                catch (Exception ex)
                {
                    TempData["Success"] = "Upload failed";
                }
            return View(smp);
        }





  public List<Sample> Listemp()
        {
            var uploadedFiles = new List<Sample>();
            var files = Directory.GetFiles(Server.MapPath("~/Images/Upload"));
            Sample uploadedFile = null;
            if (files.Count() > 0)
            {

                foreach (var file in files)
                {
                    var fileInfo = new FileInfo(file);
                    uploadedFile = new Sample() { Name = Path.GetFileName(file) };

                    uploadedFile.Path = ("/Images//Upload/") + Path.GetFileName(file);
                    uploadedFile.Size = Convert.ToString((fileInfo.Length) / 1000);
                    uploadedFiles.Add(uploadedFile);
                }
                uploadedFile.images = uploadedFiles;
            }
            return uploadedFile.images;
        }