【发布时间】:2020-12-19 03:35:06
【问题描述】:
简单用例 - 在输入选择(下拉列表)更改值后,从 AJAX 调用中动态获取 PartialView 以更新我的主页中的 div。
我采取的步骤:
- 使用@model ViewModelCreateOperation 声明的模型创建的视图(仅限,没有 PageModel)。
- 在主页上创建了复选框:
<select class="form-control" asp-items="@(new SelectList(Model.allExistingOperations))" onchange="PopulateForm(this.value); return false;"></select>
- 在主页上创建了脚本:
<script>
function PopulateForm(value) {
var dataToPost = "{ operationName:" + value + "}";;
$.ajax({
type: "post",
url: '@Url.Content("/MeaningOfLifeRoutedName")',
data: dataToPost ,
contentType : 'application/json; charset=UTF-8',
success: function (data) {
$('#lubieplacki').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr.status == 404) {
alert(thrownError);
}
}
});
}
</script>
- 在 Controllers 文件夹中创建了 Controller 以返回 PartialView(因为我不能使用“return PartialView("someview", someModel)" 和 PageModel 已经用作继承类。
namespace MyMysteriousApplication.Controllers
{
[Route("MeaningOfLifeRoutedName")]
public class MeaningOfLifeChangesController : Controller
{
private readonly MyMysteriousApplication.Models.TTSCDBContext _context;
public MeaningOfLifeChangesController(MyMysteriousApplication.Models.TTSCDBContext context)
{
_context = context;
}
public ViewModelCreateOperation viewModelCreateOperation { get; set; }
public IActionResult Index()
{
return RedirectToPage("../Index");
}
[HttpPost]
public ActionResult getMeaningOfLife(string operationName)
{
viewModelCreateOperation = new ViewModelCreateOperation();
viewModelCreateOperation = new ViewModelCreateOperation();
viewModelCreateOperation._entitiesSelectListItem = _context.Entities
.Select(a => new Microsoft.AspNetCore.Mvc.Rendering.SelectListItem()
{
Value = a.Id.ToString(),
Text = a.EntityName
}).OrderByDescending(u => u.Text)
.ToList();
viewModelCreateOperation.MeaningOfLifeChanges = _context.MeaningOfLifeChanges.Where(u => u.OperationName.Contains(operationName)).OrderBy(u => u.ChangeId).FirstOrDefault();
return PartialView("../projectManagement/partialViewCreateNewMOL", viewModelCreateOperation);
}
}
}
额外问题: 我无法以任何方式调用我的控制器(尝试了“/MeaningOfLifeChangeController/getMeaningOfLife”或“/MeaningOfLifeChange/getMeaningOfLife”,以及“~/MeaningOfLifeChangeController/getMeaningOfLife”和其他组合),所以我添加了 [Route("MeaningOfLifeRoutedName")]和方法之前的 [HttpPost]。我不明白为什么... 在启动中我添加了控制器来初始化(JSON 用于其他东西(API)):
services.AddControllersWithViews().
AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
options.JsonSerializerOptions.PropertyNamingPolicy = null;
options.JsonSerializerOptions.MaxDepth = 150;
}).AddRazorRuntimeCompilation();
【问题讨论】:
标签: json ajax asp.net-mvc razor razor-pages