我正在使用jquery ajax和json数据填充选择选项,并且它工作正常,但是当我单击提交按钮时,我的选项值变为null。这是我的代码:
查看:
@using (Html.BeginForm("Index", "Teste", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="row">
<div class="col-md-8">
Data Agendamento
</div>
<div class="col-md-8">
@Html.TextBox("DataAgendamento", null, new { @onchange = "horarios();" })
</div>
<div class="col-md-8">
Hora Agendamento
</div>
<div class="col-md-8">
<select id="HoraAgendamento" name="HoraAgendamento"></select>
</div>
<input type="submit" value="Enviar" class="btn btn-default" />
</div>
}
<script>
function horarios() {
var Dia = $('#DataAgendamento').val();
$.ajax({
url: '/Teste/Popula',
type: "GET",
dataType: "JSON",
data: { dia: Dia },
success: function (horarios) {
$("#HoraAgendamento").html("");
$.each(horarios, function (i, hora) {
console.log(i);
console.log(hora.Hora);
$("#HoraAgendamento").append(
$('<option></option>').val(hora.Id).text(hora.Hora));
});
}
});
}
</script>
我的控制器(直到问题发生)
[HttpPost]
public ActionResult Index(FormCollection form)
{
string dt_data;
dt_data = form["DataAgendamento"] + " " + form["HoraAgendamento"];
问题是我的表格[“HoraAgendamento”]为null。
答案 0 :(得分:0)
尝试使用代码
string dt_data = Request.Form["DataAgendamento"].ToString() + " " + Request.Form["HoraAgendamento"].ToString();
答案 1 :(得分:0)
我没有看到你将该值视为null的原因。我试着完成你在这里所做的事情,我可以完美地获得这个价值。请看下面我做了什么:
$(document).on('click', '#trackingaction', function ()
结果:
我的建议是检查是否从<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script>
function horarios() {
var Dia = $('#DataAgendamento').val();
$.ajax({
url: '@Url.Action("Popula")',
type: "GET",
dataType: "JSON",
data: { dia: Dia },
success: function (horarios) {
$("#HoraAgendamento").html("");
$.each(horarios, function (i, hora) {
console.log(i);
console.log(hora.Hora);
$("#HoraAgendamento").append(
$('<option></option>').val(hora.Id).text(hora.Hora));
});
}
});
}
</script>
@using (Html.BeginForm("Index1", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="row">
<div class="col-md-8">
Data Agendamento
</div>
<div class="col-md-8">
@Html.TextBox("DataAgendamento", null, new { @onchange = "horarios();" })
</div>
<div class="col-md-8">
Hora Agendamento
</div>
<div class="col-md-8">
<select id="HoraAgendamento" name="HoraAgendamento"></select>
</div>
<input type="submit" value="Enviar" class="btn btn-default" />
</div>
}
public JsonResult Popula(string dia)
{
var obj = new { Id = 1, Hora = "Drop down" };
var obj1 = new { Id = 2, Hora = "Drop down 2" };
List<Object> ob = new List<object>();
ob.Add(obj);
ob.Add(obj1);
return Json(ob, JsonRequestBehavior.AllowGet);
}
public ActionResult Index1(FormCollection form)
{
string dt_data;
dt_data = form["DataAgendamento"] + " " + form["HoraAgendamento"];
return View();
}
正确传递了Id的值。
答案 2 :(得分:0)
这是一个奇怪的解决方案,但它现在正在运作。
我刚刚用我的JavaScript中的hora.Hora替换了hora.Id
旧的:
$('<option></option>').val(hora.Id).text(hora.Hora));
新人:
$('<option></option>').val(hora.Hora).text(hora.Hora));
谢谢大家。