简体   繁体   English

MVC Core ajax 和返回结果是一个视图

[英]MVC Core ajax and return result is a view

MVC Core, NET 5, not razor pages. MVC 核心,NET 5,而不是 razor 页面。

On a view I have three select components (bootstrap-select).在一个视图中,我有三个 select 组件(引导选择)。 I populate them via ViewModel.我通过 ViewModel 填充它们。

"Get request -> Controller -> return View(viewModel);" “获取请求 -> Controller -> 返回视图(viewModel);”

What I want... When I changed value in any select component I do a post request (ajax) to the same controller (other method) and return view with repopulated data.我想要什么...当我更改任何 select 组件中的值时,我向同一个 controller (其他方法)发出一个发布请求(ajax)并返回带有重新填充数据的视图。

"'Post request -> Controller -> return View(changedModel);" "'发布请求 -> Controller -> 返回视图(changedModel);"

As I understood when I did ajax request I should handle it result in success and other cases.据我了解,当我提出 ajax 请求时,我应该处理它导致成功和其他情况。

What I should to do to reload page with new data?我应该怎么做才能用新数据重新加载页面?

Is it possible to achive this with this approach?是否有可能通过这种方法实现这一目标?

Yes, this is possible and you do not need to reload the page, just append the returned html to wherever you want it.是的,这是可能的,您不需要重新加载页面,只需 append 将返回的 html 到您想要的任何地方。

$.ajax({
    type: "POST",
    url: {your_url},
    dataType: "html",
    success: function (html) {
        $("#someDiv").html(html);
    }
});

What I should to do to reload page with new data?我应该怎么做才能用新数据重新加载页面?

If the post action return the same view as the get action and you want to reload the whole page, I think there is no need to use ajax.如果 post 操作返回与 get 操作相同的视图,并且您想重新加载整个页面,我认为没有必要使用 ajax。 You can just redirect to post action with a form submission.您可以通过表单提交重定向到发布操作。 If the view returned by the post action is a partialview you want render to the current view, you can use it like that in @cwalvoort answer.如果 post 操作返回的视图是您想要呈现到当前视图的局部视图,您可以像在 @cwalvoort 答案中那样使用它。

Based on advices of cwalvoort and mj1313基于cwalvoortmj1313的建议

I did:我做了:

  • Render main page with partials.使用局部渲染主页。 ViewModel transfered to a partial as a parameter ViewModel 作为参数传递给局部
  • On main page I added eventListners to controls with JS.在主页上,我使用 JS 将 eventListners 添加到控件中。
  • When control changes - ajax request to backend happens Controller/GetPartialView当控制发生变化时 - ajax 请求后端发生 Controller/GetPartialView
  • Result from ajax replace html in partial section ajax 的结果在部分部分替换 html
  • Programmatically show needed components, re-add eventListners以编程方式显示需要的组件,重新添加 eventListners

PS Really need to learn Blazor or UI Framework:) PS真的需要学习Blazor或者UI框架:)

Code samples:代码示例:

// JS
document.addEventListener("DOMContentLoaded", function (event) {

BindSelectActions();
});

function BindSelectActions() {

$('#selectGroups').on('hidden.bs.select', DoPartialUpdate);
$('#selectCompanies').on('hidden.bs.select', DoPartialUpdate);
$('#selectPeriods').on('hidden.bs.select', DoPartialUpdate);
}

function DoPartialUpdate(e, clickedIndex, isSelected, previousValue) {

// ToDo: Implement common script with "CallBackend" function

$.ajax({
    type: "POST",
    url: 'https://localhost:44352/TestController/TestGetPartial',
    // no data its a stub at the moment
    // data: $('#form').serialize(),
    success: function (data, textStatus) {

        $("#testControls").html(data);
        $('#selectGroups').selectpicker('show');
        $('#selectCompanies').selectpicker('show');
        $('#selectPeriods').selectpicker('show');

        BindSelectActions();
    }
});
}


// Controllers
[HttpGet]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public async Task<IActionResult> Main()
{
    // ViewModel = _helper -> _mediator -> query -> context
    return await Task.Run(() => View(new TestViewModel()));
}

[HttpPost]
[ResponseCache(NoStore = true, Location = ResponseCacheLocation.None)]
public IActionResult TestGetPartial(TestViewModel model)
{
    // ViewModel = _helper -> _mediator -> query -> context
    var result = new TestViewModel();
    result.IsPageReload = "yes";
    result.TestCollection = new string[] { "A", "B", "C" };
    result.Companies = new List<SelectListItem> { new SelectListItem { Value = "999", 
Text = "Test" } };

// ModelState.Clear();
return PartialView("_TestPartial", result);
}

// Main and partial views
@model TestViewModel

@{
    ViewData["Title"] = "Test";
}

<div id="testControls">

    @await Html.PartialAsync("_TestPartial", Model)

</div>

@section Scripts {

    <script type="text/javascript" src="~/js/test.js" asp-append-version="true"> 
</script>
}

@model TestViewModel

<form>
<div class="d-flex flex-row justify-content-between mt-4">

    <div><select id="selectGroups" asp-for="Groups" asp-items="Model.Groups" 
class="selectpicker" data-live-search="true" data-style="btn-outline-dark" 
title="Group"></select></div>
    <div><select id="selectCompanies" asp-for="Companies" asp-items="Model.Companies" 
class="selectpicker" data-live-search="true" data-style="btn-outline-dark" 
title="Company"></select></div>
    <div><select id="selectPeriods" asp-for="Periods" asp-items="Model.Periods" 
class="selectpicker" data-live-search="true" data-style="btn-outline-dark" 
title="Period"></select></div>

    <div><button type="button" class="btn btn-outline-dark">Import</button></div>
</div>
</form>

<div>
@{
    if (null != Model.TestCollection)
    {
        foreach (var item in Model.TestCollection)
        {
            <p>@item</p>
            <br>
        }
    }
}
</div>

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

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