我尝试将对象列表发送给控制器,但控制器始终将其接收为null。
var model= @Html.Raw(Json.Encode(Model.MultipleElements));
jQuery.ajax({
type: 'GET',
contentType: 'application/json',
url: '@Url.Action("AddField", "Flux")',
data: model,
success: function (response) {
$(".destinationMultiple").html(response);
}
});
这是我的控制器动作
public PartialViewResult AddField(List<Destination> model)
{
return PartialView("_myPartialView");
}
答案 0 :(得分:0)
您可以使用Ajax.Beginform。如果需要,可以执行以下操作,该步骤说明了如何将数组从View传递到Controller。
视图/控制器
namespace Testy20161006.Controllers
{
public class Destination
{
public string aDestination { get; set; }
}
public class TahtohViewModel
{
public List<Destination> MultipleElements { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public PartialViewResult AddField(List<Destination> MultipleElements)
{
List<String> sendout = new List<string>();
foreach (Destination dest in MultipleElements)
{
sendout.Add(dest.aDestination);
}
ViewBag.SendoutList = sendout;
return PartialView("_myPartialView");
}
public ActionResult Tut149()
{
Destination dest1 = new Destination { aDestination = "adest1" };
Destination dest2 = new Destination { aDestination = "adest2" };
Destination dest3 = new Destination { aDestination = "adest3" };
TahtohViewModel tahtoViewModel = new TahtohViewModel { MultipleElements = new List<Destination>() };
tahtoViewModel.MultipleElements.Add(dest1);
tahtoViewModel.MultipleElements.Add(dest2);
tahtoViewModel.MultipleElements.Add(dest3);
return View(tahtoViewModel);
}
查看
@model Testy20161006.Controllers.TahtohViewModel
@using Testy20161006.Controllers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut149</title>
<script type="text/javascript" language="javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
$(function () {
$("#theButton").click(function () {
var items = [];
var q = $("input[name='theElemsName']");
$.each(q, function (index, thevalue) {
var item = {};
item.aDestination = thevalue.value;
items.push(item);
});
jQuery.ajax({
type: 'POST',
contentType: 'application/json',
url: '@Url.Action("AddField", "Home")',
data: JSON.stringify(items),
success: function (response) {
//alert("success");
$(".destinationMultiple").html(response);
}
});
})
})
</script>
</head>
<body>
<div>
<table>
@{ var index = 0;}
@foreach (Destination item in Model.MultipleElements)
{
<tr><td>Item <span>@(index++)</span></td><td data-multipleelements="@(index)">@Html.TextBox(item.aDestination, null, new { Name = "theElemsName", Value = item.aDestination })</td></tr>
}
</table>
<input type="button" id="theButton" value="Add Field" />
<div class="destinationMultiple"></div>
</div>
</body>
</html>
局部视图
my partial view
@foreach (string item in ViewBag.SendoutList)
{
<div>@item</div>
}