Совместное использование jQuery и ASP.NET MVC.Аякс пост не работает? - PullRequest
1 голос
/ 29 мая 2011

У меня есть форма для отправки сообщения AJAX. Работает нормально.

Но когда я удаляю элемент, нажимая delete link, у меня возникает проблема, запрос на получение не публикуется.

Но из моей функции javascript вы можете видеть, что я использую jQuery css selctor, чтобы обнаружить нажатую ссылку или нет, поэтому я в замешательстве.

Вот мой код

Мой контроллер:

public class SessionsController : Controller
{
    private SessionRepository _repository;

    public SessionsController() : this(new SessionRepository()) { }

    public SessionsController(SessionRepository repository)
    {
        _repository = repository;
    }

    public ActionResult Index()
    {
        var sessions = _repository.FindAll();

        //for ajax requests, we simply need to render the partial
        if (Request.IsAjaxRequest())
            return PartialView("_sessionList2", sessions);
            //return View("_sessionList", sessions);

        return View(sessions);
    }

    [HttpPost]
    public ActionResult Add(Session session)
    {
        _repository.SaveSession(session);

        if (Request.IsAjaxRequest())
            return Index();

        return RedirectToAction("index");
    }

    [HttpPost]
    public ActionResult Remove(Guid session_id)
    {
        _repository.RemoveSession(session_id);

        return RedirectToAction("index");
    }

}

Просмотр сеанса:

@model IEnumerable<MyMVCDemo.Models.Session>


<h2>Hijax Technique</h2>    

<div id="session-list">        
    @{Html.RenderPartial("_sessionList2");}
</div>

<p>
</p>

@using (Html.BeginForm("add", "sessions", FormMethod.Post, new { @class = "hijax" }))
{
<fieldset>
    <legend>Propose new session</legend>
    <label for="title">Title</label>
    <input type="text" name="title" />

    <label for="description">Description</label>    
    <textarea name="description" rows="3" cols="30"></textarea>

    <label for="level">Level</label>
    <select name="level">
        <option selected="selected" value="100">100</option>
        <option value="200">200</option>
        <option value="300">300</option>
        <option value="400">400</option>        
    </select>

    <br />
    <input type="submit" value="Add" />
    <span id="indicator" style="display:none"><img src="../../content/load.gif"   alt="loading..." /></span>
</fieldset>

}

<label>
   <input type="checkbox" id="use_ajax" />
   Use Ajax?
</label>

<script src="../../Scripts/Common.js" type="text/javascript"></script>

Мой частичный вид:

@model IEnumerable<MyMVCDemo.Models.Session>

<table id="sessions">
<tr>
    <th>Title</th>
    <th>Description</th>
    <th>Level</th>
    <th></th>
</tr>

@if(Model.Count() == 0) {
<tr>
    <td colspan="4" align="center">There are no sessions.  Add one below!</td>
</tr>
}

@foreach (var session in Model)
{ 

    <tr>
        <td>@session.Title</td>
        <td>@session.Description</td>
        <td>session.Level</td>
        <td>   
            @Html.ActionLink("remove", "remove", new { session_id = session.Id }, new { @class = "delete" })
        </td>
    </tr>

}

Это мои javascript, которые называют ajax post:

            $('.delete').click(function () {
    if (confirm('Are you sure you want to delete this item?')) {
        $.ajax({
            url: this.href,
            type: 'POST',
            success: function (result) {
                $("#session-list").html(result);
            }
        });

        return false;
    }
    return false;
});
    $("form.hijax").submit(function (event) {
    if ($("#use_ajax")[0].checked == false)
        return;

    event.preventDefault();  //prevent the actual form post
    hijack(this, update_sessions, "html");
});

function hijack(form, callback, format) {
    $("#indicator").show();
    $.ajax({
        url: form.action,
        type: form.method,
        dataType: format,
        data: $(form).serialize(),
        completed: $("#indicator").hide(),
        success: callback
    });
}
function update_sessions(result) {
    //clear the form
    $("form.hijax")[0].reset();

    //update the table with the resulting HTML from the server
    $("#session-list").html(result);
    $("#message").hide().html("session added")
            .fadeIn('slow', function () {
                var e = this;
                setTimeout(function () { $(e).fadeOut('slow'); }, 2000);
            });
}

1 Ответ

2 голосов
/ 29 мая 2011

Мне кажется, что вы не перепривязываете событие клика после обновления партиала.

Что происходит, так это то, что вы заменяете DOM (с которым связаны события), когда делаете вызов ajax. Поэтому после того, как вы обновите форму, все ваши события исчезнут.

В jquery есть живое событие, которое поможет вам здесь.

Приведенный ниже код не проверен, некоторые могут быть с ним проблемы, но он должен дать вам представление.

var sessionList = $('#session-list'); 
$('.delete', sessionList).live('click', function () {
    if (confirm('Are you sure you want to delete this item?')) {
        $.ajax({
            url: this.href,
            type: 'POST',
            success: function (result) {
                sessionList.html(result);
            }
        });

        return false;
    }
    return false;
});

Селектор $ ('. Delete', sessionList) предназначен для того, чтобы дать живой функции контекст, чтобы она не раздувала события до самого верха.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...