Can’t get my head around this Jquery problem I have..
I’ve been looking around and found some solutions but they don’t seem to work.
I have a MVC project and in one view I am using sortable and that works like a charm.
The problem is when I want to send the new order of my list back to the controller..
I’m using alert(items) and it shows me the string I want..
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>ArrangeAttributesViewModel</legend>
<div id="contentWrap">
<p>
</p>
<p>
</p>
<div>
_category.CategoryName</div>
<div id="attributeList" class="container">
<ul>
@foreach (var _category in Model.AttributeList)
{
<li id="@("a_" + _category.CategoryID.ToString())">
@_category.CategoryName
</li>
}
</ul>
</div>
<p>
</p>
<p>
<input type="submit" id="SaveButton" value="Save Changes" />
</p>
</div>
</fieldset>
}
And here is the script:
<script type="text/javascript">
$(document).ready(function () {
$("li").hover(function () {
$(this).css('cursor', 'move');
$(this).css('background-color', '#2c87b2');
},
function () {
$(this).css('cursor', 'auto');
$(this).css('background-color', '#5c87b2');
});
$("#attributeList ul").sortable({
opacity: 0.6,
cursor: 'move',
update: function () {
items = $(this).sortable('toArray');
alert(items);
}
});
var items;
$("#SaveButton").click(function () {
alert(items);
$.post({
url: '/Profile/ArrangeCategories',
type: 'POST',
data: { items: items },
traditional: true
});
});
});
</script>
I’m using
[AcceptVerbs(HttpVerbs.Post), Authorize]
public ActionResult ArrangeCategories(int ProfileID, string[] items)
in the controller..
Any help much appreciated!
Edit:
I’ve changed the code a bit after some user input..
Now everything works fine up until the sending of the variable, in other words I see the alert when I press the button…
Ok, so I solved the problem..
Firstly, I defined the input to the controller as a
string[], which is incorrect. It’s supposed to be aList<string>.Secondly, I changed the
$.postto$.ajax, this is what I ended up with (ignore the change of variable name, items to itemIds):Hope this is usefull to someone else!