简体   繁体   English

在 ASP 3.1 RazorPages AJAX 发布更新模型后,Razor 不会将值打印到屏幕上

[英]Razor not printing Values to screen after ASP 3.1 RazorPages AJAX Post Updates Model

Hello I am updating a model with an AJAX call on the event of a dropdown selection.您好,我正在使用 AJAX 调用在下拉选择事件中更新模型。 The model is updated and when I step through the below razor loop the values exist.模型已更新,当我逐步执行以下剃刀循环时,值存在。 However nothing inside the @if statement prints to the screen, not even the H2.但是,@if 语句中的任何内容都不会打印到屏幕上,甚至 H2 也不行。 The div is just empty... Thoughts? div 只是空的... 想法?

@if (Model.FieldsRequiredOnStart != null)
{
    foreach (var item in Model.FieldsRequiredOnStart)
    {
        for (int i = 0; i < @item.Inputs.Count(); i++)
        {
            <h2>Fields Required on Start</h2>
            var x = @item.Inputs[i];

            <span>@x.Name</span>
            <input placeholder="@x.Name" maxlength="@x.MaxSize" type="@x.InputType"> <input />
        }
    }
}

function onSelect(e) {
        let id = $("#wfDropdown").data("kendoDropDownList").value()
        if (e.item) {    
            $('#wfDefId').val(id)
        } else {
            $('#wfDefId').val(id)
        }
            
        $.ajax({
            type: 'Post',
            url: '/CreateNewWorkflow?handler=RequiredInputs',
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            data: { Id: id },
            success: function () {                      
            }            
        });
    }

EDIT ON SUCCESS: I ended up using the Partial View solution.成功编辑:我最终使用了部分视图解决方案。 My issue was I was not sending a refreshed model when I had previously tried the partial way.我的问题是当我之前尝试部分方式时,我没有发送更新的模型。 The Second answer is also valid.第二个答案也有效。 Gotcha: If you make a partial be sure to remove the @Page reference at the top or you will get Model is null errors.问题:如果您制作了部分内容,请务必删除顶部的 @Page 引用,否则您将收到 Model is null 错误。

Also worth noting the C# Syntax I had to use was slightly different than what is provided in the answer to return the Partial view..另外值得注意的是,我必须使用的 C# 语法与返回 Partial 视图的答案中提供的略有不同。

 public ActionResult OnPostRequiredInputs(int id)
        {            
             //DO STUFF 
            //Refresh Model to pass to partial
            IEnumerable<Razor.PageModels.CreateWorkflowNames> namelist = da.GetWfDefVersionNameAndIds();

            var freshModel = new CreateNewWorkflowModel(_cache, _mapper, _wlog, _workflowFactory, _configuration)
            {
                FieldsRequiredOnStart = entityDefinitionFieldsList,
                CreateWorkflowModel = namelist
            };
            
            return Partial("/Pages/_CreateNewWorkflowRequiredFieldsPartial.cshtml", freshModel);

        }

Assuming your CreateNewWorkflow controller action returns a model rehydrated with the new data, you should be able to set that new data in the onSuccess callback of your ajax request.假设您的 CreateNewWorkflow 控制器操作返回一个用新数据重新水化的模型,您应该能够在 ajax 请求的 onSuccess 回调中设置该新数据。

I'd do this to accomplish the result.我会这样做以实现结果。

  1. Create partial view for the razor we're gonna need to refresh.为我们需要刷新的剃刀创建局部视图。
//Filename: YourView.cshtml
<div id="partialWrapper"></div>

//File name: _YourPartialView.cshtml
@if (Model.FieldsRequiredOnStart != null)
{
    foreach (var item in Model.FieldsRequiredOnStart)
    {
        for (int i = 0; i < @item.Inputs.Count(); i++)
        {
            <h2>Fields Required on Start</h2>
            var x = @item.Inputs[i];

            <span>@x.Name</span>
            <input placeholder="@x.Name" maxlength="@x.MaxSize" type="@x.InputType"> <input />
        }
    }
}
  1. Make sure your controller action returns a partial view.确保您的控制器操作返回部分视图。
public IActionResult<YourModelClass> CreateNewWorkflow(YourRequestClass request) {
   //your logic
   //...

  var rehydratedModel = new YourModelClass(); //actually fill this with data
  return PartialView(rehydratedModel);
}
  1. Set the partial view result to your wrapper div in the onSuccess call back.在 onSuccess 回调中将部分视图结果设置为您的包装器 div。
function onSelect(e) {
        let id = $("#wfDropdown").data("kendoDropDownList").value()
        if (e.item) {    
            $('#wfDefId').val(id)
        } else {
            $('#wfDefId').val(id)
        }
            
        $.ajax({
            type: 'Post',
            url: '/CreateNewWorkflow?handler=RequiredInputs',
            beforeSend: function (xhr) {
                xhr.setRequestHeader("XSRF-TOKEN",
                    $('input:hidden[name="__RequestVerificationToken"]').val());
            },
            data: { Id: id },
            success: function (data) {  //data represents your partial view       
              $('#partialWrapper').html(data)    //set partial view         
            }            
        });

That is a pretty typical flow of how you refresh razor pages with ajax.这是一个非常典型的使用 ajax 刷新剃刀页面的流程。

Razor not printing Values to screen after ASP 3.1 RazorPages AJAX Post Updates Model, The div is just empty在 ASP 3.1 RazorPages AJAX 发布更新模型后,Razor 不打印值到屏幕,div 只是空的

The issue is related to the Ajax success function, according to your code, we can see that you didn't do anything to update the page with the latest data.该问题与 Ajax 成功函数有关,根据您的代码,我们可以看到您没有执行任何操作以使用最新数据更新页面。

Generally, after getting the latest data in the success function, we could use JQuery to find the page elements and bind the latest data or populate the new page element to replace the old data.一般在success函数中获取到最新数据后,我们可以使用JQuery查找页面元素并绑定最新数据或者填充新的页面元素来替换旧数据。 You could refer to the following sample code:您可以参考以下示例代码:

    <select id="ddl1" asp-for="CategoryId" asp-items="Model.Categories">
        <option value="">Select Category</option>
    </select>
    <h4>SubCategories</h4> 

    @if (Model.SubCategories != null)
    {
        <table >
            <tr><th>SubCategoryId</th><th>CategoryId</th><th>SubCategoryName</th></tr>
            <tbody id="tbody"> 
                @foreach (var item in Model.SubCategories)
                {
                    <tr>
                        <td>@item.SubCategoryId</td>
                        <td>@item.CategoryId</td>
                        <td>@item.SubCategoryName</td>
                    </tr>
                }
            </tbody>
        </table>
    }

Code in the cshtml.cs file: cshtml.cs 文件中的代码:

    private ICategoryService _categoryService;
    public DDLpageModel(ICategoryService categoryService)
    {
        _categoryService = categoryService;
    }
    [BindProperty(SupportsGet = true)]
    public int CategoryId { get; set; }
    public int SubCategoryId { get; set; }
    public SelectList Categories { get; set; }

    public List<SubCategory> SubCategories { get; set; }
    public void OnGet()
    {
        Categories = new SelectList(_categoryService.GetCategories(), nameof(Category.CategoryId), nameof(Category.CategoryName));
        SubCategories = _categoryService.GetSubCategories(1).ToList();
    }
    public JsonResult OnGetSubCategories()
    { 
        return new JsonResult(_categoryService.GetSubCategories(CategoryId));
    }

Then, in the Ajax success function, find the element and set the value or dynamic add page elements with the latest data and replace the old one.然后,在Ajax成功函数中,找到该元素并设置值或动态添加最新数据的页面元素并替换旧的。

    @section scripts{ 
        <script>
            $(function () {
                $("#ddl1").on("change", function () {
                    var categoryId = $(this).val(); 
                    //method 1: using JQuery Ajax get the latest data and update the main page content
                    $.ajax({
                        url: `?handler=SubCategories&categoryId=${categoryId}`,
                        contentType: 'application/json; charset=utf-8',
                        type: 'get',
                        dataType: 'json',
                        success: function (data) {
                            $("#tbody").html("");
                            //loop through the data and append new data to the tbody
                            $.each(data, function (i, item) { 
                                $("#tbody").append("<tr><td>" + item.subCategoryId + "</td><td>" + item.categoryId + "</td><td>" + item.subCategoryName + "</td></tr>");
                            });
                        }
                    });
                });  
            });
        </script>
    }

Besides, you could also create a Partial page (for example: _SubCategories.cshtml):此外,您还可以创建一个 Partial 页面(例如:_SubCategories.cshtml):

    @model List<SubCategory>
    <table class="table table-striped"> 
        <tr><th>SubCategoryId</th><th>CategoryId</th><th>SubCategoryName</th></tr>
        <tbody id="tbody">
            @foreach (var item in Model)
            {
                <tr>
                    <td>@item.SubCategoryId</td>
                    <td>@item.CategoryId</td>
                    <td>@item.SubCategoryName</td>
                </tr>
            }
        </tbody>
    </table>

In the main page .cshtml.cs file, add the following handler:在主页 .cshtml.cs 文件中,添加以下处理程序:

    public PartialViewResult OnGetSubcategoryPartial()
    {
        var subcategories = _categoryService.GetSubCategories(CategoryId).ToList();
        return Partial("_SubCategories", subcategories);
    }

Then, using JQuery Ajax to call the above handler and load the partial page:然后,使用 JQuery Ajax 调用上述处理程序并加载部分页面:

    <h2>Using Partial Page</h2>
    <select id="ddl2" asp-for="CategoryId" asp-items="Model.Categories">
        <option value="">Select Category</option>
    </select>
    <div id="output">
    </div>

    @section scripts{ 
        <script>
            $(function () { 
                $("#ddl2").on("change", function () {
                    var categoryId = $(this).val(); 
                    $.ajax({
                        url: `?handler=SubcategoryPartial&categoryId=${categoryId}`,
                        contentType: 'application/html; charset=utf-8',
                        type: 'get',
                        dataType: 'html',
                        success: function (result) {
                            $("#output").html("");
                            $("#output").append(result);
                        }
                    });
                }); 
            });
        </script>
    }

The screenshot like this:截图是这样的:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM