Jquery Ajax in Asp.net MVC (Part 16)


In this post i will show you how to use Jquery Ajax method in Asp.net MVC. This topic is very vast but I will create very simple example to test this method in asp.net MVC.

calling_jquey_ajax

Step 1: Create one blank asp.net MVC application. I hope you are knowing the basic concept of asp.net MVC.

Step 2: Create Emp Class in Model folder and write the code like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace AjaxDemoInMVC.Models
{
    public class Emp
    {
        public int Id { get; set; }
        public string EmpName { get; set; }
        public string EmpAddress { get; set; }
    }
}

Step 3: Create the HomeController and the DisplayEmpDetail Method like this


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AjaxDemoInMVC.Models;

namespace AjaxDemoInMVC.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public JsonResult DisplayEmpDetail(int id)
        {
            Emp obj = new Emp
            {
                 Id=id,
                 EmpName="Chandradev",
                 EmpAddress="Bangalore"
            };
            return Json(obj);
        }
    }
}

Note: Here we are returning the values as Json format.

Step 4: Create the Index view and Write the code for calling the method using Jquery Ajax method as given below


@model AjaxDemoInMVC.Models.Emp

@{
    ViewBag.Title = "Index";
}

<fieldset>
    <legend>
        Sample code for Calling Jquery Ajax in asp.net MVC
    </legend>

    <br />

EmpId: <input type="text" id="txtId" />
<input type="button" id="btnAjax"  value="Click Here to Call Jquery Ajax" />
</fieldset>
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script>
    $(function () {
        $("#btnAjax").click(function () {
            $.ajax({
                type: "POST",
                url: "Home/DisplayEmpDetail",
                data: '{Id: "' + $("#txtId").val() + '" }',
                contentType: "application/json; charset=utf-8",
                success: function (response) {
                    alert("EmpName: "+ response.EmpName + "   EmpAddress: " + response.EmpAddress);
                },
                failure: function (response) {
                    alert(response.responseText);
                },
                error: function (response) {
                    alert(response.responseText);
                }

            });

        });

    });
</script>

Note : In the above code we show that we are using jquery Ajax method on button Click event and Ajax method expect the type, URL,Data,ContentType,Success,Failure and error parameter.

Type: means Type of Request in Ajax method

URL: Means Method name which are using for Ajax functionality.

data: what are the input data being used in method

ContentType: What are the content type consuming in Ajax method. We are giving data in Json format in DisplayEmpDetail Method.

success: What will return the method on successfully execution.

failure: It will define what message should be display on failure of Ajax method
error: It will display the error message.

Summary: We show that how to use Jquery Ajax method in asp.net MVC application.

webgrid reference is not found in asp.net view


While working with Webgrid in asp.net mvc, I was not getting the reference in view. Then i fixed the issue like this,

Step 1: Firstly i added the System.web.helper dll

Step 2: I went to the property of dll and change CopyLocal to True.

webgrid

How to display the warning message in asp.net mvc ?


Warning_Msg

while working in asp.net mvc we will get scenario to display the alert or warning message while deleting or editing the record, then we can achieve that functionality by using this code as given below


// Alert message for edit record
@Html.ActionLink("Edit","Index",new {Id=item.Id},new { onclick = "return confirm('Are you sure do you want to edit the record ?');" })
// Alert message for delete the record.
@Html.ActionLink("Delete","Delete",new {Id=item.Id},new { onclick = "return confirm('Are you sure you wish to delete this record "+@item.Id +"?');" })

How to make multiline text box in asp.net MVC


If you are working on asp.net mvc and you got the scenario to make Multiline text box, where user can enter the long text.

Then you can do like this

Step 1 : Take the @html.TextAreaFor html helper

Step 2: Increase the height and weight of TextArea like this

@Html.TextAreaFor(model => model.Answer,5, 55, null)

Note : Here Model.Answer is the part of my model class.

How to upload multiple files in Asp.net MVC ?


MultipleFile

There are so many ways to do this task in asp.net MVC. But this is one of the easiest ways to upload multiple file.
In this approach we are using Html 5.0 fileupload control. If the browser will not support HTML 5 then it will display in traditional ways.

Step1: Create the blank asp.net mvc application and write the UI code in index view like this


@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div id="multiple">
        <input type="file" class="multiple" name="files" multiple />
    </div>
    <div id="single">
        <input type="file" class="single" name="files" /><br />
        <input type="file" class="single" name="files" /><br />
        <input type="file" class="single" name="files" /><br />
    </div>
    <button class="btn btn-default">Upload</button>
}

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

    <script type="text/javascript">
        $(function () {
            if(window.FileReader != null){
                $('#single').hide();
                $('.single').prop('disabled', true);
            } else {
                $('#multiple').hide();
                $('.multiple').prop('disabled', true);
            }
        });
    </script>

Note: If the browser doesn’t support html 5 then this jquery script code will activate Single fileupload option.

Step 2: Write the code in Home controller for file upload like this given below



using System;
using System.Collections.Generic;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace MultipleFileUpload.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult FileUpload(IEnumerable<HttpPostedFileBase> files)
        {
            foreach (var file in files)
            {
                if (file != null && file.ContentLength > 0)
                {
                    file.SaveAs(Path.Combine(Server.MapPath("/Images"), Guid.NewGuid() + Path.GetExtension(file.FileName)));
                }
            }
            return View("Index");
        }
    }
}

Summary: We show that how to upload multiple file in asp.net MVC.

How to upload file on asp.net mvc ?


FileUpload

So many time, beginner in asp.net mvc will ask this question. I will show on basic demo for this functionality.

Step 1: Create the Index view like this

@{
    ViewBag.Title = "Index";
}


@using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

    <label for="file">Upload Image:</label>
    <input type="file" name="file" id="file" /><br><br>
    <input type="submit" value="Upload Image" />
    <br><br>
    @ViewBag.Message
}

Step 2: Write the code in Home Controller for file upload like this

using System;
using System.IO;
using System.Web;
using System.Web.Mvc;

namespace ImageUpload_MVC.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult FileUpload(HttpPostedFileBase file) 
        {
            if (file != null && file.ContentLength > 0)
                try
                {
                    string path = Path.Combine(Server.MapPath("~/Images"),
                                               Path.GetFileName(file.FileName));
                    file.SaveAs(path);
                    ViewBag.Message = "File uploaded successfully";
                }
                catch (Exception ex)
                {
                    ViewBag.Message = "ERROR:" + ex.Message.ToString();
                }
            else
            {
                ViewBag.Message = "You have not specified a file.";
            }
            return View("Index");
            //return RedirectToAction("Index", "Home");
        }
    }
}
 

Note: Don’t forget to keep Images folder in application

Summary:

We show the basic file upload functionality in asp.net MVC.

How to implement multiple submit button in asp.net MVC ?


In Asp.net MVC there are so many ways to implement the multiple submit button in single view.
I have already written one post using attribute-based solution

But there are still so many other approaches to do this task like

1. Using Multiple button with different Name
2. Using Multiple button with Same Name
3. using HTML 5 Foraction and Formmethod
4. using using Jquery Click event

Here I am going to show all the 4 approaches in single view and controller for sake of simplicity

Step 1: Create the Emp class in Model folder like this

namespace MultipleSave.Models
{
    public class Emp
    {
        public int Id { get; set; }
        public string EmpName { get; set; }
        public string EmpAddress { get; set; }
        public string  EmailId { get; set; }
    }
}

Step 2: Keep the all UI related code in Index view

@model MultipleSave.Models.Emp

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>


@using (Html.BeginForm("ProcessForm","Home",FormMethod.Post)) 
{
    <b>Method 1</b>
    @Html.AntiForgeryToken()

    @Html.EditorForModel()
    <br />
    <input type="submit" name="save" value="Save" />
    <input type="submit" name="cancel" value="Cancel" />
    <br />
    @ViewBag.msg

}
<br />

@using (Html.BeginForm("SaveData", "Home", FormMethod.Post))
{
    <b>Method 2</b>
    @Html.AntiForgeryToken()

    @Html.EditorForModel()
    <br />
    <input type="submit" name="submit" value="Save" />
    <input type="submit" name="submit" value="Cancel" />
    <br />
    @ViewBag.msg1

}

<br />

@using (Html.BeginForm())
{
    <b>Method 3 using HTML 5 Foraction and Formmethod</b>
    @Html.AntiForgeryToken()

    @Html.EditorForModel()
    <br />
    <input type="submit" name="save" value="Save"
           formaction="SaveForm" formmethod="post" />
    <input type="submit" name="cancel" value="Cancel"
                   formaction="CancelForm" formmethod="post" />
    <br />
    @ViewBag.msg2

}

<br />

@using (Html.BeginForm())
{
    <b>Method 4 using Jquery</b>
    @Html.AntiForgeryToken()

    
    <br />
    @Html.EditorForModel()
    <br />
    <input type="submit" id="save" value="Save" />
    <input type="submit" id="cancel" value="Cancel" /><br />
                @ViewBag.msg3

}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
    $(document).ready(function () {

        $("#save").click(function () {
            $("form").attr("action", "/home/Saveform1");
        });

        $("#cancel").click(function () {
            $("form").attr("action", "/home/Cancelform1");
        });

    });
</script>

Step 3: Write the C# code in Home Controller like this


using MultipleSave.Models;
using System.Web.Mvc;

namespace MultipleSave.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }

        //Method 1 Multiple button with different Name
        [HttpPost]
        public ActionResult ProcessForm(Emp obj,string save,string cancel)
        {
            if(!string.IsNullOrEmpty(save))
            {
                ViewBag.msg = "Emp saved successfully";
            }
            if(!string.IsNullOrEmpty(cancel))
            {
                ViewBag.msg = "The operation was cancelled";
            }
            return View("Index", obj);
        }

        // Method 2 Multiple button with Same Name
        [HttpPost]
        public ActionResult SaveData(Emp obj, string submit)
        {
            switch (submit)
            {
                case "Save":
               ViewBag.msg1 = "Emp saved successfully";
                    break;
                case "Cancel":
                    ViewBag.msg = "The operation was cancelled";
                    break;
            }
            return View("Index", obj);
        }

        //Method 3: using HTML 5 features
        [HttpPost]
        public ActionResult SaveForm(Emp obj)
        {
            ViewBag.msg2 = "Emp saved successfully";
            return View("Index", obj);
        }

        //Method 3: using HTML 5 features
        [HttpPost]
        public ActionResult CancelForm(Emp obj)
        {
            ViewBag.msg2 = "The operation was cancelled";
            return View("Index", obj);
        }

        //Method 4: using Jquery
        [HttpPost]
        public ActionResult SaveForm1(Emp obj)
        {
            ViewBag.msg3 = "Emp saved successfully";
            return View("Index", obj);
        }

        //Method 4: using Jquery
        [HttpPost]
        public ActionResult CancelForm1(Emp obj)
        {
            ViewBag.msg3 = "The operation was cancelled";
            return View("Index", obj);
        }

    }
}

Summary:
Here we show that how to handle the multiple submit button in single view with so many ways.