whoah
whoah

Reputation: 4443

mvc ajax/jquery - click image without reload page

  1. User clicks image on my MVC view and then this onclick event calling some method or action in controler - without reloading page. This method will returns some string to my jquery/ajax function (some data). With this data I can change image border (problem - without reload). Any examples how can I do this?

  2. User fill textbox, then clicks button - without reloading page - it will add to database content of this textbox and show all of records from database. The same question - how to start?

Regards

Upvotes: 2

Views: 2943

Answers (2)

Denys Wessels
Denys Wessels

Reputation: 17049

I've created a sample project for you answering both question, you can get it here from Google drive(Select File->Download to download the .zip folder), either have a look at the sample project or follow steps below:

Question 1 - Change image border on click

1) Add an Image controller to the Controllers folder:

public class ImageController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public int ChangeImageSize()
    {
        return 10;
    }
}

2) Right click on the Index method and select "Add View..." leave the name as Index

Add the following markup to the Index view, basically what it does is execute a jQuery function which goes to the ChangeImageSize method in your Image controller and returns a random value of 10.I then set the border width of the image to this value (and no page refresh!)

@{
    ViewBag.Title = "Index";
}
<script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#imageLink').on("click", "a,img", function (e) {
            e.preventDefault();
            $.get("@Url.Action("ChangeImageSize","Image")",function(data)
            {
                $("#image").css("border-width",data);
            });
        });
    });
</script>
<h2>
    Index</h2>
<a id="imageLink" href="javascript:;">
    <img id="image" src="../../Images/image.jpg" style="width: 300px; height: 300px;" />
</a>

Question 2 - Insert a value in database, display a list containing the new value:

1) Add an ADO.NET Entity Data Model to your models folder and connect to the required DB (alternatively use any other data access methodology, I've just went with EF because it's simple)

2) Add an Employee controller to the controllers folder:

public class EmployeeController : Controller
{
    EmployeeModel dataContext = new EmployeeModel();
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(string employeeName)
    {
        if (!String.IsNullOrEmpty(employeeName))
        {
            Employee emp = new Employee() { EmployeeName = employeeName };
            dataContext.Employees.AddObject(emp);
            dataContext.SaveChanges();
        }

        List<Employee> employees = dataContext.Employees.ToList();
        return View("Partial/AllEmployees",employees);
    }
}

3)Right click on the Index action method and choose "Add View..." leave the name as Index

4) Copy the following markup to the Index View

@{
    ViewBag.Title = "Employees";
}
<script src="../../Scripts/jquery-1.7.1.js" type="text/javascript"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $(function () {
            $('form').submit(function () {
                $.ajax({
                    url: this.action,
                    type: this.method,
                    data: $(this).serialize(),
                    success: function (result) {
                        $('#result').html(result);
                    }
                });
                return false;
            });
        });

        $.post("@Url.Action("Index","Employee")",function(data)
        {
            $("#result").html(data);
        });
    });
</script>

@using (Ajax.BeginForm(new AjaxOptions()))
{
    <div>
        Enter your name : @Html.TextBox("employeeName") 
        <input type="submit" value="Insert" />
    </div>
}
<div id="result"></div>

5) Under Views->Employee Create a folder called Partial

6) Add a new View To the Partial folder called - AllEmployees.cshtml

7) Add the following mark up to the AllEmployees view:

@model IEnumerable<MVCSample.App.Models.Employee>

@{
    Layout = null;
}

<table>
    <tr>
        <th>
            Employee name
        </th>
    </tr>
@foreach (var item in Model) {
    <tr>
        <td>@Html.DisplayFor(modelItem => item.EmployeeName)</td>
    </tr>
}
</table>

Upvotes: 1

Reza Abolfathi
Reza Abolfathi

Reputation: 3191

try learning about Ajax.BeginForm. this covers both your questions.

this is a sample :

@using (Ajax.BeginForm(new AjaxOptions { UpdateTargetId = "updateDiv" }))
{
    <div>
        Enter your name : @Html.TextBox("name") <input type="submit" />
    </div>
}
<div id="updateDiv">

</div>

Upvotes: 1

Related Questions