问题描述
我想制作一个动态表格,这就是我所拥有的:
Create.cshtml视图
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<select id="SCat_Cat" name="SCat_Cat" asp-for="Cat_Id" asp-items="(SelectList)ViewBag.Cat_ID" class="form-control" onchange="funct()">
<option value="0">Select Category</option>
</select>
<select id="SCat_SCat" name="SCat_SCat" asp-for="SCat_ID" asp-items="(SelectList)ViewBag.Scat_ID" class="form-control">
<option value="0">Select Sub-Category</option>
</select>
</form>
选择类别后运行的脚本:
<script type="text/javascript">
function funct() {
var catvalue = document.getElementById("SCat_Cat").value;
alert(catvalue);
$.ajax(
{
type: "POST",url: '?CatID=' + catvalue,success: function (result) {
if (result.success) {
alert("Good");
}
},error: function (req,status,error) {
alert("Error");
}
});
return false;
}
</script>
控制器:
public async Task<IActionResult> Create(string CatID)
{
ViewBag.Cat_ID = new SelectList(_context.Category,"Cat_ID","Cat_Name");
if (CatID == null)
{
ViewBag.SCat_ID = new SelectList("");
}
else
{
List<SubCategory> AllSubCategories = _context.SubCategory.ToList();
List<SubCategory> SelectedSubCategories = AllSubCategories.FindAll(a => a.SCat_Cat.Contains(CatID));
ViewBag.SCat_ID = new SelectList(SelectedSubCategories,"SCat_ID","SCat_Name");
}
return View();
}
到目前为止,这是我想出的最成功的方法,但是它重置了包括CSS在内的所有内容。唯一正确的方法是用我需要的东西填充保管箱。
解决方法
编辑: 使用如下扩展方法创建静态类:
public static class HttpRequestExtensions
{
private const string RequestedWithHeader = "X-Requested-With";
private const string XmlHttpRequest = "XMLHttpRequest";
public static bool IsAjaxRequest(this HttpRequest request)
{
if (request == null)
{
throw new ArgumentNullException("request");
}
if (request.Headers != null)
{
return request.Headers[RequestedWithHeader] == XmlHttpRequest;
}
return false;
}
}
现在像这样修改您的控制器方法:
public async Task<IActionResult> Create(string CatID)
{
ViewBag.Cat_ID = new SelectList(_context.Category,"Cat_ID","Cat_Name");
if (CatID == null)
{
ViewBag.SCat_ID = new SelectList("");
}
else
{
List<SubCategory> AllSubCategories = _context.SubCategory.ToList();
List<SubCategory> SelectedSubCategories = AllSubCategories.FindAll(a => a.SCat_Cat.Contains(CatID));
ViewBag.SCat_ID = new SelectList(SelectedSubCategories,"SCat_ID","SCat_Name");
}
return Request.IsAjaxRequest() ? (IActionResult)PartialView() : View();
}
因此,如果请求是ajax请求,并且您的js像这样,则只能返回PartialView:
<script type="text/javascript">
function funct() {
var catvalue = document.getElementById("SCat_Cat").value;
alert(catvalue);
$.ajax(
{
type: "POST",url: '?CatID=' + catvalue,success: function (result) {
document.getElementById("myDiv").innerHTML = result;
alert("Good");
},error: function (req,status,error) {
alert("Error");
}
});
return false;
}
例如,您可以将表单插入ID为“ myDiv”的div中。