I'm trying with no success for 4 days now, I'm a Junior Dev, so that's why.
Context:
I have a flexigrid where I show the data collected from database, in a very particular column, there's a checkbox, I create a javascript function that gets the entity Id when you click on the checkbox and stores it on an javascript array, that I want to send to an ActionResult.
Problem:
I can pass using Ajax, but I can't render the ActionResult view, I get 404. Trying to use a @Html.ActionLinkbut doens't reconize the javascript array.
So how it's the way I can post the javascript array to a controller and follow that controller flow, like render another view with another URL ?
Javascript Array:
var arrayId = new Array();
View:
<a href="@Url.Action("SomeAction", "SomeController", new { area = "SomeArea", arrayId = arrayId })">
Controller:
public ActionResult SomeAction(object[] arrayId) { //some code return View("AnotherView"); }
Ways to solution:
Ajax, if I can render the view in another URL.
HTML '< Form >', if I can pass the javascript array.
Or C# Helper, maybe passing the javascript array to a view model, but I don't know how to.
PartialView? Not a solution.
...that I want to send to a ActionResult.
I believe you may have a little confusion here. In ASP.NET MVC, anything that receives a request, either from AJAX or a full request, is an action. The result of that action, like a JSON response or a full page result, is an ActionResult.
Always think about it like request > response. Request is handled by your action, response is what the action outputs.
Now, to your question. Consider this page as the first one, that outputs the IDs from the DB:
<form method="post" action="/home/someaction">
<ul>
<li><label><input type="checkbox" name="arrayId" value="1" />1</label></li>
<li><label><input type="checkbox" name="arrayId" value="2" />2</label></li>
<li><label><input type="checkbox" name="arrayId" value="3" />3</label></li>
<li><label><input type="checkbox" name="arrayId" value="4" />4</label></li>
</ul>
<button>Post array to action SomeAction</button>
</form>
<script type="text/javascript">
$(function(){
$('form').on('submit', function () {
$('checkbox:checked').each(function (ix, el) {
$(el).attr('name', 'arrayId[' + ix + ']');
});
});
});
</script>
Let's see what's going on here:
arrayId[0]. This is required. ASP.NET uses the name attr to bind the received data to what the action expects. If it's a collection (like a list or an array), the name must also include a 0-based indexer. That's what we're doing before posting the form.The action that will receive this post looks like:
[HttpPost]
public ActionResult SomeAction(string[] arrayId)
{
return View(arrayId);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With