Tuesday, March 31, 2015

Ajax partial view mvc update

http://www.blackbeltcoder.com/Articles/script/using-ajax-beginform-with-asp-net-mvc

https://cmatskas.com/update-an-mvc-partial-view-with-ajax/

http://blog.falafel.com/ajaxbeginform-with-mvc-4/

http://stackoverflow.com/questions/5410055/using-ajax-beginform-with-asp-net-mvc-3-razor

http://stackoverflow.com/questions/1440151/asp-net-mvc-ajax-form-loadingelementid





AjaxScript.js :

$(document).ready(function () {
    $("#ajax-loader").css("display", "none");
});

function OnBegin() {
    $("#divMsg").html("Beginning Ajax request.");
}
function OnComplete() {
    $("#divMsg").html("Completing Ajax request.");
}
function OnSuccess(response) {
    $("#searchresults").html(response);
    }

function OnFailure(response) {
    $("#searchresults").html("Whoops! That didn't go so well did it?");
}

view index.cstml
<div  class="panel-body">
    @using (Ajax.BeginForm("PerformAction", new AjaxOptions
     {
        InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace,
        HttpMethod="POST",
        OnBegin=" OnBegin",
        OnSuccess = "OnSuccess",
        OnFailure = "OnFailure" ,
        LoadingElementDuration = 1000,
        LoadingElementId = "ajax-loader",
        UpdateTargetId = "searchresults"
    }))
    {
        <fieldset>
            @Html.LabelFor(m => m.EmailAddress)
            @Html.TextBoxFor(m => m.EmailAddress)
            @Html.ValidationMessageFor(m => m.EmailAddress)
            <input type="submit" value="Submit" />
        </fieldset>
    }
    <div id="ajax-loader">
        <img src="~/Images/ajax-loader.gif" 
 Style="display:none"/>
    </div>
    <div id="searchresults"></div>
    <div id="divMsg"></div>
</div>


namespace TestAjaxFrom.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new AjaxDemoModel();
            return View();
        }

        [HttpPost]
        public ActionResult PerformAction(AjaxDemoModel model)
        {
            try
            {
                // Perform tasks here
               

                return Content("Action was successfully completed!");
            }
            catch (Exception)
            {
                return Content("Oh no! Looks like we ran off into a ditch on that one!");
            }
        }
    }
}

viewmodel

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

using System.ComponentModel.DataAnnotations;
namespace TestAjaxFrom.ViewModels
{
    public class AjaxDemoModel
    {
        [Required]
        [Display(Name = "Email address")]
        public string EmailAddress { get; set; }
    }
}

No comments:

Post a Comment