【发布时间】:2021-04-10 07:03:47
【问题描述】:
我试图实现以下目标:假设我有一个 Create VM 表单。这都是非常标准的东西:
型号
[BindProperty]
public NewVM NewVM { get; set; }
NewVM 模型(部分):
public string Name { get; set; }
public int SelectedTemplateId { get; set; }
public List<Templates> Templates { get; set; }
模板模型(部分):
public int Id{ get; set; }
public string Name { get; set; }
表格(部分)
<form method="post">
<div class="form-group row">
<label for="vmname" class="col-sm-4 col-form-label col-form-label-sm">Virtual Machine Name</label>
<div class="col-sm-8">
<input type="text" class="form-control form-control-sm">
</div>
</div>
</form>
创建 VM 表单的一部分是选择模板。这取决于所选的集群。这是一个下拉框
<div class="form-group row">
<label class="col-sm-4 col-form-label col-form-label-sm">Cluster</label>
<div class="col-sm-8">
@Html.DropDownListFor(x => Model.ClusterId, new SelectList(Model.Clusters, "Id", "Name"), "Please select", htmlAttributes: new { @class = "form-control form-control-sm", id = "clusters" })
@Html.ValidationMessageFor(x => x.Tenant.ClusterId, "", new { @class = "text-danger" })
</div>
</div>
到目前为止一切顺利。选择群集时,将进行以下Ajax调用以检索该群集可用的模板:
Javascript:
$(function () {
$("#clusters").change(function () {
var host = $(this).val();
$.ajax({
type: "POST",
url: "/VM/AddVmDC2?handler=GetTemplates",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { "host": host },
success: function (response) {
$("#templatebody").html(response);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
后台
public async Task<IActionResult> OnPostGetTemplates(int clusterid)
{
_apilocation = _config["apiurl"];
var templates = await helper.QueryApi(_apilocation, "/api/inventory/template?clusterid=" + clusterid);
NewVM.Templates = JsonConvert.DeserializeObject<List<Templates>>(templates);
return Partial("_Templates", Tenant);
}
局部视图
@model NewVM
@Html.DropDownListFor(x => x.SelectedTemplateId , new SelectList(Model.Templates, "Id", "Name"), "Please select", htmlAttributes: new { @class = "form-control form-control-sm", id = "templates" })
@Html.ValidationMessageFor(x => x.SelectedTemplateId , "", new { @class = "text-danger" })
Form中调用部分视图
<div class="form-group row">
<label class="col-sm-4 col-form-label col-form-label-sm">Templates</label>
<div class="col-sm-8" id="templatebody">
@{
<partial name="_Templates" for="NewVM"/>
}
</div>
</div>
问题是当我发布表单时 SelectedTemplateId 始终为空。我在这里做错了什么。有人可以帮我解释为什么 SelectedTemplateId 总是为空。
谢谢!
【问题讨论】:
标签: ajax asp.net-core razor-pages