Core 2 Razor页面-AJAX和部分视图 [英] Core 2 Razor Page - AJAX and Partial Views

查看:89
本文介绍了Core 2 Razor页面-AJAX和部分视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Core 2 MVC Web应用程序,正在尝试向其中添加一些Ajax.

我有一个Create视图,该视图加载了标准的Web表单.这与到目前为止我学到/完成的内容有所不同的是,我想在页面上添加一些半动态内容.

页面的ViewModel是一堆简单的属性,但其中一部分也是嵌套的集合.

我试图通过模式将值动态添加到嵌套集合中,然后重新加载部分视图以反映我添加的内容,而不会导致页面重新加载-我只想重新加载部分视图并关闭Modal./p>

我可以看到JS正在处理请求并触发对控制器的调用并获得200响应,但它没有关闭模态或用Modal中的数据重新加载部分视图.

有些事情我绝对不会到达这里.有人可以建议吗?

ViewModel

 公共类RaceViewModel{公开Race Race Race {放;}公共ObservableCollection< CurrencyDetails>货币{get;放;}public CurrencyDetails BaseCurrency {get;放;}public CurrencyDetails RaceCurrency {get;放;}公共ObservableCollection< RaceOptions>RaceOptionData {get;放;}[DisplayFormat(DataFormatString ="{0:0.00")]公共十进制BaseFee {get;放;}} 

主视图(省略了省略号部分)

  @using TechsportiseOnline.Helpers@model TechsportiseOnline.ViewModels.RaceViewModel@ {ViewData ["Title"] =创建";}< h2>创建新的比赛</h2>< div class ="modal fade bd-example-modal-lg" tabindex =-1" role ="dialog" aria-labelledby ="myLargeModalLabel" aria-hidden ="true" id ="optionsmodal">< div class ="modal-dialog modal-lg">< div class ="modal-content">< div class ="modal-header">< button type ="button" class ="close" data-dismiss ="modal" aria-label ="Close">< span aria-hidden ="true"& times;</span></button>< h2 class ="modal-title">新竞赛选项</h2></div>< div class ="modal-body">< div class ="row">< div class ="col-md-4">< div class ="form-group">< label value =名称" class ="control-label">选项名称</label>< br/>< small class ="text-muted">此竞赛选项的名称</small><输入名称=名称"占位符=您的10k" type ="text" class ="form-control" aria-label =名称">@ *< span asp-validation-for ="RaceData.Name" class ="text-danger"></span> * @</div></div>< div class ="col-md-4">< div class ="form-group">< label name ="RaceDistance" value ="Race Distance" class ="control-label"&Distance</label>< br/>< small class ="text-muted">选择比赛距离,用于年龄分级</small><选择name ="RaceDistance" class ="form-control">< option value =" selected> --select-</option>< option value ="M1"> 1英里</option>< option value ="KM5"> 5 km</option>< option value ="KM6"> 6 km</option>< option value ="M4"> 4英里</option>< option value ="KM8"> 8 km</option>< option value ="M5"> 5英里</option>< option value ="KM10"> 10 km</option>< option value ="KM12"> 12 km</option>< option value ="KM15"> 15 km</option>< option value ="M10"> 10英里</option>< option value ="KM20"> 20 km</option>< option value ="Half">半程马拉松</option>< option value ="KM25"> 25 km</option>< option value ="KM30"> 30 km</option>< option value ="Marathon"> Marathon</option>< option value ="KM50"> 50 km</option>< option value ="M50"> 50英里</option>< option value ="KM100"> 100 km</option>< option value ="KM150"> 150 km</option>< option value ="M100"> 100英里</option>< option value ="KM200"> 200 km</option>< option value ="Other"> Other</option></select>< br/>@ *< span asp-validation-for ="RaceData.RaceDistance" class ="text-danger"></span> * @</div></div>< div class ="col-md-4">< div class ="form-group">< label name ="MaxEntries" value ="Maximum Entries" class ="control-label"> Maximum Entries</label>< br/>< small class ="text-muted">种族的最大容量</small>< input name ="MaxEntries" class ="form-control"/>@ *< span asp-validation-for ="RaceData.MaxEntries" class ="text-danger"></span> * @</div></div></div>< div class ="row">< div class ="col-md-4">< div class ="form-group">< label name =开始时间" value =开始时间" class ="control-label">种族开始时间</label>< br/>< small class ="text-muted"> HH:MM</small>中的开始时间<输入名称=开始时间" value ="19:00" asp-format ="{0:hh:mm}" class ="form-control" type ="time"/>@ *< span asp-validation-for ="RaceData.RaceStartTime" class ="text-danger"></span> * @</div></div>< div class ="col-md-4">< div class ="form-group">< label value ="Entry Price" class ="control-label"> Entry Price</label>< br/>< small class ="text-muted">正常比赛项目的价格</small><输入名称=输入价格" type ="text" class ="form-control" aria-label =数量"占位符="10.00" asp-format ="{0:0.00}">@ *< span asp-validation-for ="RaceData.EntryPrice" class ="text-danger"></span> * @</div></div>< div class ="col-md-4">< div class ="form-group">< label class ="control-label">会员折扣</label>< br/>< small class ="text-muted">成为联盟跑步者的折扣值</small><输入名称="AffiliatedDiscountValue"类型=文本" class =表单控制" aria-label =金额" value ="2.00" asp-format ="{0:0.00}">@ *< span asp-validation-for ="AffiliatedDiscountValue" class ="text-danger"></span> * @</div></div></div></div>< div class ="modal-footer">< button type ="button" class ="btn btn-default" data-dismiss ="modal"> Cancel</button>< button type ="button" class ="btn btn-primary" id ="addoption"> Add</button></div></div></div></div>< form asp-action =创建" enctype ="multipart/form-data">< div asp-validation-summary ="ModelOnly" class ="text-danger"></div>< div class ="panel panel-default">< div class ="panel-heading">种族选项</div>< div class ="panel-body">< div id ="container">如果您想在同一事件中拥有多个距离/种族,请在此处创建不同的竞赛选项".您必须至少有1个竞赛选项.< div id ="dvRaceOptionsResults">@ {Html.RenderPartial("RaceOptions",Model);}</div>< button type ="button" class ="btn btn-primary" data-toggle ="modal" data-target =.bd-example-modal-lg">添加竞赛选项</button></div></div></div></div></div></div></div></div>< div class ="form-group">< input type ="submit" value ="Create" class ="btn btn-default"/></div></form>< div>< ap-action ="Index">返回列表</a></div>@section脚本{@ {await Html.RenderPartialAsync("_ ValidationScriptsPartial");}< script type ="text/javascript">$(#addoption").click(function(){$ .ajax({url:'@ Url.Action("GetRaceOptions","Races")',输入:"POST",成功:功能(数据){if(data){//检查是否定义了数据$(#dvRaceOptionsResults").html(data);}}});});</script>} 

局部视图

  @model TechsportiseOnline.ViewModels.RaceViewModel< table>< thead>< tr>< th>名称</th></tr></thead>< tbody>@if(Model.RaceOptionData!=空){foreach(Model.RaceOptionData中的var选项){< tr>< td> @ option.Name</td></tr>}}</tbody></table> 

控制器方法

  [HttpPost]公共异步Task< IActionResult>GetRaceOptions(RaceViewModel种族){var viewModel = race;返回PartialView("RaceOptions",viewModel);} 

解决方案

您正在调用没有 data:参数的ajax.因此,您不会将数据发布到您的控制器.比控制器尝试返回带有空viewModel的部分视图.如果要保存新添加的选项,则需要执行以下操作.

  1. 创建数据对象并将其作为数据参数发送到ajax中.

  2. 修改控制器以保存新选项并返回旧+新选项

      [HttpPost]公共异步Task< IActionResult>GetRaceOptions(RaceViewModel种族){//保存RaceViewModel中的选项//获取旧选项+新添加的选项var viewModel =旧+新添加的数据返回PartialView("RaceOptions",viewModel);} 

您需要在ajax的成功部分中关闭模式

 成功:function(data){if(data){//检查是否定义了数据$(#dvRaceOptionsResults").html(data);$('#modalId').modal('hide');} 

I have a Core 2 MVC web app which I am trying to add some Ajax into.

I have a Create view which loads a standard web form. What makes this a bit different to what I have learned/done so far is that I would like to add some semi-dynamic content to the page.

The ViewModel for the page is a bunch of simple properties, but part of it is also a nested collection.

I am trying to dynamically add values into the nested collection via a modal, and then reload the partial view to reflect what I have added without causing a page reload - I only want to reload the partial view and close the Modal.

I can see the JS is actioning the request and firing the call to the controller and getting a 200 response but it is not closing the modal or reloading the partial view with the data from the Modal.

There is something I am definitely not getting here. Can anyone advise?

ViewModel

public class RaceViewModel
    {
        public Race RaceData { get; set; }
        public ObservableCollection<CurrencyDetails> Currencies { get; set; }
        public CurrencyDetails BaseCurrency { get; set; }
        public CurrencyDetails RaceCurrency { get; set; }
        public ObservableCollection<RaceOptions> RaceOptionData { get; set; }
        [DisplayFormat(DataFormatString = "{0:0.00")]
        public decimal BaseFee { get; set; }
    }

Main view (Irrelevant sections omitted)

    @using TechsportiseOnline.Helpers
    @model TechsportiseOnline.ViewModels.RaceViewModel

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

    <h2>Create a new race</h2>

    <div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true" id="optionsmodal">
        <div class="modal-dialog modal-lg">

            <div class="modal-content">
                <div class="modal-header">

                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h2 class="modal-title">New Race Option</h2>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label value="Name" class="control-label">Option Name</label>
                                <br /><small class="text-muted">The name of this Race Option</small>
                                <input name="Name" placeholder="Your 10k" type="text" class="form-control" aria-label="Name">
                                @*<span asp-validation-for="RaceData.Name" class="text-danger"></span>*@
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label name="RaceDistance" value="Race Distance" class="control-label">Distance</label>
                                <br /><small class="text-muted">Choose a race distance, used for Age Grading </small>

                                <select name="RaceDistance" class="form-control">
                                    <option value="" selected>--select--</option>
                                    <option value="M1">1 mile</option>
                                    <option value="KM5">5 km</option>
                                    <option value="KM6">6 km</option>
                                    <option value="M4">4 miles</option>
                                    <option value="KM8">8 km</option>
                                    <option value="M5">5 miles</option>
                                    <option value="KM10">10 km</option>
                                    <option value="KM12">12 km</option>
                                    <option value="KM15">15 km</option>
                                    <option value="M10">10 miles</option>
                                    <option value="KM20">20 km</option>
                                    <option value="Half">Half Marathon</option>
                                    <option value="KM25">25 km</option>
                                    <option value="KM30">30 km</option>
                                    <option value="Marathon">Marathon</option>
                                    <option value="KM50">50 km</option>
                                    <option value="M50">50 miles</option>
                                    <option value="KM100">100 km</option>
                                    <option value="KM150">150 km</option>
                                    <option value="M100">100 miles</option>
                                    <option value="KM200">200 km</option>
                                    <option value="Other">Other</option>
                                </select><br />
                                @*<span asp-validation-for="RaceData.RaceDistance" class="text-danger"></span>*@
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label name="MaxEntries" value="Maximum Entries" class="control-label">Maximum Entries</label>
                                <br /><small class="text-muted">The maximum capacity of the race</small>


                                <input name="MaxEntries" class="form-control" />
                                @*<span asp-validation-for="RaceData.MaxEntries" class="text-danger"></span>*@
                            </div>
                        </div>
                    </div>

                    <div class="row">         
                        <div class="col-md-4">
                            <div class="form-group">
                                <label name="Start Time" value="Start Time" class="control-label">Race Start Time</label>
                                <br /><small class="text-muted">Start time in HH:MM</small>
                                <input name="Start Time" value="19:00" asp-format="{0:hh:mm}" class="form-control" type="time" />
                                @*<span asp-validation-for="RaceData.RaceStartTime" class="text-danger"></span>*@
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="form-group">
                                <label value="Entry Price" class="control-label">Entry Price</label>
                                <br /><small class="text-muted">The price of the normal race entry</small>
                                <input name="Entry Price" type="text" class="form-control" aria-label="Amount" placeholder="10.00" asp-format="{0:0.00}">
                                @*<span asp-validation-for="RaceData.EntryPrice" class="text-danger"></span>*@
                            </div>
                        </div>

                        <div class="col-md-4">
                            <div class="form-group">
                                <label class="control-label">Affiliation Discount</label>
                                <br /><small class="text-muted">Value of discount for being an affiliated runner</small>
                                <input name="AffiliatedDiscountValue" type="text" class="form-control" aria-label="Amount" value="2.00" asp-format="{0:0.00}">
                                @*<span asp-validation-for="AffiliatedDiscountValue" class="text-danger"></span>*@
                            </div>
                        </div>               
                    </div>






                    </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                            <button type="button" class="btn btn-primary" id="addoption" >Add</button>
                        </div>
                    </div>
                </div>
    </div>









    <form asp-action="Create" enctype="multipart/form-data">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                <div class="panel panel-default">
                        <div class="panel-heading">Race Options</div>
                        <div class="panel-body">
                            <div id="container">
                                Create your different Race Options here, if you want to have more than one distance/race in the same event. You must have at least 1 Race Option.
                                <div id="dvRaceOptionsResults">
                                    @{Html.RenderPartial("RaceOptions", Model);}
                                </div>
                                <button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-lg">Add Race Option</button>
                            </div>
                        </div>
                    </div>


                </div>

                    </div>
                </div>
            </div>

        </div>
        <div class="form-group">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </form>






    <div>
        <a asp-action="Index">Back to List</a>
    </div>

    @section Scripts {
        @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
        <script type="text/javascript">
            $("#addoption").click(function(){
            $.ajax({
                url: '@Url.Action("GetRaceOptions", "Races")',
                type: 'POST',
                success: function(data) {
                    if (data) {  // check if data is defined
                        $("#dvRaceOptionsResults").html(data);
                    }
            }
        });
    });
        </script>

    }

Partial View

    @model TechsportiseOnline.ViewModels.RaceViewModel
    <table>
        <thead>
            <tr>
                <th>Name</th>
            </tr>
        </thead>
        <tbody>
            @if (Model.RaceOptionData != null)
            {
                foreach (var option in Model.RaceOptionData)
                {
                <tr>
                    <td>@option.Name</td>
                </tr>
                }
            }
        </tbody>
    </table> 

Controller Method

[HttpPost]
public async Task<IActionResult> GetRaceOptions(RaceViewModel race)
   {
       var viewModel = race;
       return PartialView("RaceOptions", viewModel);
   }

解决方案

You are calling ajax without data: parameter. So you are not posting data to your controller. Than controller is trying to return the partial view with empty viewModel. If you want to save newly added options you will need to do something like this.

  1. create data object and send it as data parameter in ajax.

  2. modify the controller to save new options and return old + new options

    [HttpPost]
    public async Task<IActionResult> GetRaceOptions(RaceViewModel race)
    {
       //save options from RaceViewModel
    
       //get old options + newly added options
    
       var viewModel = old + newly added data
       return PartialView("RaceOptions", viewModel);
    }
    

You need to close modal in the success part of ajax

success: function(data) {
                if (data) {  // check if data is defined
                    $("#dvRaceOptionsResults").html(data);
                    $('#modalId').modal('hide');
                }

这篇关于Core 2 Razor页面-AJAX和部分视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆