views:

29

answers:

1

I've got index of my elements:

<h2>Index</h2>
    <script type="text/javascript"
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
    <script type="text/javascript">
        $(document).ready(function () {
            $('button').click(function () {
                $.post("Home/Swap", $("#log").serialize(), function (data) {
                    $("#log").load("Home/Index #log");
                });
              });

         }); 
    </script> 

   <form name="list" action="<%=Url.Action("Post", "Home")%>" method="post" id="log">
    <% foreach (var k in Model) { %>
        <input type="checkbox" id="ids" name="ids" value="<%=k.pos%>" /><%= k.pos %>. To jest numer: <%=k.name%><br />
    <% } %>

    </form>
    <button>Swap</button>

and Swap method:

    public ActionResult Swap(int[] ids)
    {
        int pos1=ids[0];
        int pos2=ids[1];
        Element element1 = (from t in db.Elements
                            where t.pos == pos1
                            select t).Single();
        Element element2 = (from t in db.Elements
                            where t.pos == pos2
                            select t).Single();



        element1.pos = pos2;
        element2.pos = pos1;
        db.SaveChanges();

        return Index();
    }

Everything works fine at the first swap of elements. But when I swap it once, and then try to swap another two I get an exception:

System.NullReferenceException was unhandled by user code
Message=Object reference not set to an instance of an object.

(exception from Swap Method) It's JQuery problem, Im sure. I susspect this $("#log").load("Home/Index #log"); line - it shows me right result, but doesn't work fine if I try to do it more then once. how to fix it?

edit: when I refresh page it works the same -> first works well, after getting an exception (the first touched elements are swaped after refreshing)

A: 

When you do .load("url selector") it gets that element, not the contents of that element, so you end up with a nested <form>, so instead create a wrapper and load that wrapper, so you replace the <form>, like this:

<div id="wrapper">
<form name="list" action="<%=Url.Action("Post", "Home")%>" method="post" id="log">
  <% foreach (var k in Model) { %>
    <input type="checkbox" id="ids" name="ids" value="<%=k.pos%>" /><%= k.pos %>. To jest numer: <%=k.name%><br />
  <% } %>
  </form>
</div>
<button>Swap</button>

Then load that element instead, so you're replacing the <form>, like this:

$(function () {
  $('button').click(function () {
    $.post("Home/Swap", $("#log").serialize(), function (data) {
      $("#wrapper").load("Home/Index #log");
    });
  });
});
Nick Craver
it works ;) thx4ya help ;)
trn