我正在尝试使用ajax将值传递给我的控制器。
ajax代码如下:
var myId = $(".slectOne[checked]").attr("data-id");
$.ajax({
url: '@Url.Action("reservation_step_1", "Home")',
type: 'POST',
data: { id: myId },
});
控制器代码如下:
[HttpPost]
[AllowAnonymous]
public ActionResult reservation_step_1(string id)
{
string val = id;
return RedirectToAction("reservation_step_2", "Home", new { val = val });
}
我不确定我是否做错了什么,但控制器中的“ id”值为“ null”。
答案 0 :(得分:0)
这肯定可以。
控制器
public class HomeController : Controller
{
[HttpPost]
public ActionResult reservation_step_1(string id)
{
string val = id;
return RedirectToAction("reservation_step_2", "Home", new { val = val });
}
//my controller action name, yours is different
public ActionResult Tut118()
{
return View();
}
查看
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut118</title>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$("#theButton").click(function () {
//kudos to https://stackoverflow.com/questions/5450104/using-jquery-to-get-all-checked-checkboxes-with-a-certain-class-name
var myId = $('.slectOne:checkbox:checked').attr("data-id");
$.ajax({
type: "Post",
url: '@Url.Action("reservation_step_1", "Home")',
data: { 'id': myId },
dataType: 'json',
success: function (data) {
$.each(data, function (i, anObj) {
$("#Asentamientos").append($('<option>').text(anObj.Text).attr('value', anObj.Value));
});
}
});
})
//kudos to https://stackoverflow.com/questions/9709209/html-select-only-one-checkbox-in-a-group
// the selector will match all input controls of type :checkbox
// and attach a click event handler
$("input:checkbox").on('click', function () {
// in the handler, 'this' refers to the box clicked on
var $box = $(this);
if ($box.is(":checked")) {
// the name of the box is retrieved using the .attr() method
// as it is assumed and expected to be immutable
var group = "input:checkbox[name='" + $box.attr("name") + "']";
// the checked state of the group/box on the other hand will change
// and the current value is retrieved using .prop() method
$(group).prop("checked", false);
$box.prop("checked", true);
} else {
$box.prop("checked", false);
}
});
})
</script>
</head>
<body>
<div>
<h3>CheckBoxes</h3>
<label>
<input data-id="1" type="checkbox" class="slectOne" value="1" name="fooby[1][]" />CheckBox1
</label>
<label>
<input data-id="2" type="checkbox" class="slectOne" value="1" name="fooby[1][]" />CheckBox2
</label>
<label>
<input data-id="3" type="checkbox" class="slectOne" value="1" name="fooby[1][]" />CheckBox3
</label>
</div>
<input type="button" id="theButton" value="PassData" />
</body>
</html>