【问题标题】:cannot get parameters from ajax call to controller razor无法从 ajax 调用中获取参数到控制器剃须刀
【发布时间】:2020-12-19 03:35:06
【问题描述】:

简单用例 - 在输入选择(下拉列表)更改值后,从 AJAX 调用中动态获取 PartialView 以更新我的主页中的 div。

我采取的步骤:

  1. 使用@model ViewModelCreateOperation 声明的模型创建的视图(仅限,没有 PageModel)。
  2. 在主页上创建了复选框:
<select class="form-control" asp-items="@(new SelectList(Model.allExistingOperations))" onchange="PopulateForm(this.value); return false;"></select>
  1. 在主页上创建了脚本:
<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>
  1. 在 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


    【解决方案1】:

    这不是我的答案,但孟佳东在 ASP .NET 论坛中帮助了我。我正在发布他的答案:

    由于你要发送的数据只是一个字符串类型的数据,你需要像下面这样对它进行字符串化。

    var dataToPost = JSON.stringify(value);
    

    那么在你的 Action 中,你还应该添加 [FromBody] 属性。

    public ActionResult getMeaningOfLife([FromBody]string operationName)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-20
      • 2018-12-16
      • 1970-01-01
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多