代码改变世界

asp.net mvc working with ajax

2013-01-17 23:50  yezhi  阅读(261)  评论(0编辑  收藏  举报

提交内容后更新

action:

public ActionResult Index()
        {
            return View(_entities.GuestSet.ToList());
        }

        // POST: /GuestBook/Create

        public ActionResult Create(Guest guestToCreate)
        {
            _entities.AddToGuestSet(guestToCreate);
            _entities.SaveChanges();

            return PartialView("Guests", _entities.GuestSet.ToList());
        }

view:

<script src="http://www.cnblogs.com/Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>
    <script src="http://www.cnblogs.com/Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>

    <h1>Guest Book</h1>

    <% using (Ajax.BeginForm("Create", new AjaxOptions {UpdateTargetId="divMessages" }))
       { %>
    
        <label for="Name">Your Name:</label>
        <br /><%= Html.TextBox("Name")%>
        
        <br /><br />
        
        <label for="Message">Message:</label>
        <br /><%= Html.TextArea("Message")%>
    
        <br /><br />
        
        <input type="submit" value="Add Message" />
    
    <% } %>

    <div id="divMessages">
        <% Html.RenderPartial("Guests"); %>
    </div>
<% foreach (var item in Model) { %>
    <div>
        <h3><%= Html.Encode(item.Name) %></h3>
        
        <%= Html.Encode(item.Message) %>
    </div>
<% } %>

异步提交

action:

public ActionResult Index()
        {
            return View(_entities.MovieSet.ToList());
        }

        // GET: /Movie/Create

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

        // POST: /Movie/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public string Create(Movie movieToCreate)
        {
            try
            {
                _entities.AddToMovieSet(movieToCreate);
                _entities.SaveChanges();
                return "Inserted new movie " + movieToCreate.Title;
            }
            catch
            {
                return "Could not insert movie " + movieToCreate.Title;
            }
        }

view:

create

<script src="http://www.cnblogs.com/Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>
    <script src="http://www.cnblogs.com/Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>

    <script type="text/javascript">

        function createSuccess(context)
        {
            alert( context.get_data());
        }
    
    </script>


    <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>

    <% using (Ajax.BeginForm(new AjaxOptions {OnSuccess="createSuccess"}))
       {%>

        <fieldset>
            <legend>Create Movie</legend>
            <p>
                <label for="Title">Title:</label>
                <%= Html.TextBox("Title")%>
                <%= Html.ValidationMessage("Title", "*")%>
            </p>
            <p>
                <label for="Director">Director:</label>
                <%= Html.TextBox("Director")%>
                <%= Html.ValidationMessage("Director", "*")%>
            </p>
            <p>
                <label for="DateReleased">DateReleased:</label>
                <%= Html.TextBox("DateReleased")%>
                <%= Html.ValidationMessage("DateReleased", "*")%>
            </p>
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>

    <% } %>

    <div>
        <%=Html.ActionLink("Back to List", "Index") %>
    </div>

显示进度条

action:

[AcceptVerbs(HttpVerbs.Post)]
        public string Create(Movie movieToCreate)
        {
            Thread.Sleep(5 * 1000);
            try
            {
                _entities.AddToMovieSet(movieToCreate);
                _entities.SaveChanges();
                return "Inserted new movie " + movieToCreate.Title;
            }
            catch
            {
                return "Could not insert movie " + movieToCreate.Title;
            }
        }

view:

<script src="http://www.cnblogs.com/Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>
    <script src="http://www.cnblogs.com/Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>

    <script type="text/javascript">

        function createSuccess(context)
        {
            alert( context.get_data());
        }
    
    </script>

    <div id="divLoading" style="display:none">
        <image src="../Content/Busy.gif" alt="posting form" />    
    </div>

    <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>

    <% using (Ajax.BeginForm(new AjaxOptions {OnSuccess="createSuccess", LoadingElementId="divLoading"}))
       {%>

        <fieldset>
            <legend>Create Movie</legend>
            <p>
                <label for="Title">Title:</label>
                <%= Html.TextBox("Title")%>
                <%= Html.ValidationMessage("Title", "*")%>
            </p>
            <p>
                <label for="Director">Director:</label>
                <%= Html.TextBox("Director")%>
                <%= Html.ValidationMessage("Director", "*")%>
            </p>
            <p>
                <label for="DateReleased">DateReleased:</label>
                <%= Html.TextBox("DateReleased")%>
                <%= Html.ValidationMessage("DateReleased", "*")%>
            </p>
            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>

    <% } %>

    <div>
        <%=Html.ActionLink("Back to List", "Index") %>
    </div>

异步检索内容

action:

public ActionResult Index()
        {
            return View(_entities.CategorySet.ToList());
        }


        public ActionResult Details(int id)
        {
            var products = from p in _entities.ProductSet
                           where p.CategoryId == id
                           select p;
            return PartialView("Details", products);
        }

view:

<script src="http://www.cnblogs.com/Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="http://www.cnblogs.com/Scripts/MicrosoftAjax.debug.js" type="text/javascript"></script>
<script src="http://www.cnblogs.com/Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>

<script type="text/javascript">

    $(pageReady);

    function pageReady()
    {
        $("#categories a").click( selectLink );
    }

    function selectLink()
    {
        $("#categories a.selected").removeClass("selected");
        $(this).addClass("selected");
    }
    

</script>

<ul id="categories" style="display:inline">
<% foreach (var category in Model)
   { %>

    <li style="display:inline">
        <%= Ajax.ActionLink(category.Name, "Details", new {id=category.Id}, new AjaxOptions {UpdateTargetId="divDetails"}) %>
    </li>

<% } %>
</ul>

<hr />

<div id="divDetails"></div>

异步删除

action:

[AcceptVerbs(HttpVerbs.Delete)]//ajax
        public ActionResult Delete(int id)
        {
            var movieToDelete = (from m in _entities.MovieSet
                                 where m.Id == id
                                 select m).FirstOrDefault();
            _entities.DeleteObject(movieToDelete);
            _entities.SaveChanges();
            return PartialView("Movies", _entities.MovieSet.ToList());
        }

        [ActionName("Delete")]
        public ActionResult Delete_GET(int id)
        {
            var movieToDelete = (from m in _entities.MovieSet
                                 where m.Id == id
                                 select m).FirstOrDefault();
            return View(movieToDelete);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [ActionName("Delete")]
        public ActionResult Delete_POST(int id)
        {
            var movieToDelete = (from m in _entities.MovieSet
                                 where m.Id == id
                                 select m).FirstOrDefault();
            _entities.DeleteObject(movieToDelete);
            _entities.SaveChanges();
            return RedirectToAction("Index");
        }

view:

<ul>
    <% foreach (var movie in Model)
       { %>
    
        <li>
            <%= movie.Title %>
            <%= Ajax.ActionLink("Delete", "Delete", new {id=movie.Id}, new AjaxOptions {HttpMethod="DELETE", Confirm="Delete record?", UpdateTargetId="divMovies" })%>
        </li>
    
    <% } %>

</ul>

Using the AcceptAjax Attribute

attribute:

public sealed class AcceptAjaxAttribute : ActionMethodSelectorAttribute
{
public override bool IsValidForRequest(ControllerContext
➥controllerContext, MethodInfo methodInfo)
{
if (controllerContext == null)
{
throw new ArgumentNullException(“controllerContext”);
}
return controllerContext.HttpContext.Request.IsAjaxRequest();
}
}

controller:

public class SelectorController : Controller
{
private ProductsDBEntities _entities = new ProductsDBEntities();
public ActionResult Index()
{
var categories = _entities.CategorySet.ToList();
var products = new List<Product>();
return View(new ProductsVDM(categories, products));
}
[AcceptAjax]
[ActionName(“Details”)]
public ActionResult Details_Uplevel(int id)
{
var products = from p in _entities.ProductSet
where p.CategoryId == id
select p;
return PartialView(“Details”, products);
}
[ActionName(“Details”)]
public ActionResult Details_Downlevel(int id)
{
var categories = _entities.CategorySet.ToList();
var products = from p in _entities.ProductSet
where p.CategoryId == id
select p;
return View(“Index”, new ProductsVDM(categories, products));
}
}