ASP.NET MVC 5个POST checkboxfor上用onclick使用Ajax控制器(A

2019-10-28 22:54发布

我是相当新的MVC所以请多多包涵。

我手头的目标是张贴含有称为“验证”来使用Ajax我的控制器属性checkboxfor HTML帮手。 我做的研究土堆,并取得了这个职位非常类似,但它仍然没有达到控制器,而是我收到一个505错误。 checkboxfor阿贾克斯链接 。 这个帖子没有显示控制器如何处理被传递到数据,我带领相信这可能是我的问题,但我不能肯定。 或者,它可能是一些与在foreach块做一些怪异的东西。(边注上表中,我们使用的表格格式datatables.net库)。 下面是我的代码...

模型(直接从EF实体类来得快,经由元数据带来的)

namespace Entities
{
public class FPDrinkingWater : AccessibleRecord<FPDrinkingWater>
{
    public FPDrinkingWater();

    public bool Approved { get; set; }
    public string ApprovedBy { get; set; }
    public DateTime? ApprovedDate { get; set; }
    public string Clorinated { get; set; }
    public DateTime? CollectionDate { get; set; }
    public TimeSpan? CollectionTime { get; set; }
    public string Collectors { get; set; }
    public string Comments { get; set; }
    public override string CreatedBy { get; set; }
    public override DateTime CreatedDate { get; set; }
    public bool Deleted { get; set; }
    public bool EC { get; set; }
    public override int Id { get; set; }
    public string Location { get; set; }
    public bool RAG { get; set; }
    //
    // Summary:
    //     Drinking water record
    public override string RecordName { get; }
    public short? Replicate { get; set; }
    public virtual SampleLog SampleLog { get; set; }
    public int SID { get; set; }
    public bool SWAT_LAB { get; set; }
    public bool TIMS { get; set; }
    public override string UpdatedBy { get; set; }
    public override DateTime? UpdatedDate { get; set; }
    public bool Verified { get; set; }
    public string VerifiedBy { get; set; }
    public DateTime? VerifiedDate { get; set; }

    public override void UpdateTo(FPDrinkingWater entity);

    protected override void ParameterChecks();
    }
}

控制器的动作来填充观点:

//unverified Drinking Water log
    [OpenAction]
    public async Task<ActionResult> UnverifiedDrinkingWaterLog(AlertModel alert)
    {
        //return partial Drinking water log view
        return await UnverifiedDataTableAsync<FPDrinkingWater>(alert);
    }

定义UnverifiedDataTableAsync

 //Unverified data table
    [OpenAction]
    public async Task<ActionResult> UnverifiedDataTableAsync<TEntity>(AlertModel alert, string viewName = null) where TEntity : class
    {
        // get data

        var data = (from a in await LimsManager.AllAsync<TEntity>()
                    select a).ToList();
        //LimsManager.AllAsync returns the entire context contents  of the Entity in a List then the view tests if `Verified` is not populated.

        // create sample log model with alert

        var response = new TableModel<TEntity>
        {
            Alert = alert,
            Data = data
        };

        // return partial data view
        return PartialView(viewName ?? $"_Unverified{typeof(TEntity).Name}Table", response);
    }

控制器更新动作:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> VerifyDrinkingWater(FPDrinkingWater drinkingWater, string id )
    {
        //create alert model
        var response = new AlertModel();

        //check model state
        if(ModelState.IsValid)
        {
            //add the verifier to the DrinkingWater record
            drinkingWater.Verified = true;
            drinkingWater.VerifiedBy = User.Identity.Name;
            drinkingWater.VerifiedDate = DateTime.Now;

            //update the drinking water with the new verified information
            var result = await LimsManager.UpdateAsync(drinkingWater);

            //check update result
            if(result.Succeeded)
            {
                response.AddInfo($"All SID's successfully verified in the database.", BSContextualTypes.success);
            }
            else
            {
                //add failure to alert
                response.AddInfo($"Unable to verify SID's in database.", BSContextualTypes.warning);
            }
        }
        else
        {
            InvalidState(response);
        }
        return await UnverifiedDrinkingWaterLog(response);
    }

视图应遍历实体的背景下,建设了表中的每个记录发现未经验证:

@model MyProgram.Application.TableModel<Entities.FPDrinkingWater>
@{
Layout = null;

var insertionMode = InsertionMode.Replace;
var fail = "displayFailure";
var target = "UnverifiedDrinkingWaterContent";
var ajax = "UnverifiedDrinkingWaterLogLoader";
var verify = Html.UserHasClaim("FP/DrinkingWater/VerifyDrinkingWater");


}

<br />

@if (Model != null && Model.Alert != null && Model.Alert.Message != null)
{
    @Html.Alert(Model.Alert)
}

@MyHelper.Loader(ajax)
<table id="UnverifiedDrinkingWaterTable" class="table table-hover">
    <thead>
    <tr>
        <th>@Html.LabelFor(m => m.Data.FirstOrDefault().SID)</th>
        <th>@Html.LabelFor(m => m.Data.FirstOrDefault().Location)</th>
        <th>@Html.LabelFor(m => m.Data.FirstOrDefault().Replicate)</th>
        <th>@Html.LabelFor(m => m.Data.FirstOrDefault().CollectionDate)</th>
        <th>@Html.LabelFor(m => m.Data.FirstOrDefault().CollectionTime)</th>
        <th>@Html.LabelFor(m => m.Data.FirstOrDefault().Collectors)</th>
        <th>@Html.LabelFor(m => m.Data.FirstOrDefault().Clorinated)</th>
        <th>@Html.LabelFor(m => m.Data.FirstOrDefault().Comments)</th>
        <th>@Html.LabelFor(m => m.Data.FirstOrDefault().Verified)</th>
    </tr>
    </thead>
    <tbody>
   @if (Model.Data.Any(v => !v.Verified))
   {
   foreach (var log in Model.Data.Where(v => !v.Verified))
   {
    <tr data-record-id="@log.Id">
        <td>@log.SID</td>
        <td>@log.Location</td>
        <td>@log.Replicate</td>
        <td>@log.CollectionDate.Value.ToShortDateString()</td>
        <td>@log.CollectionTime</td>
        <td>@log.Collectors</td>
        <td>@log.Clorinated</td>
        <td>@log.Comments</td>
        <td>@Html.CheckBoxFor(m => log.Verified, new { data_url = Url.Action("VerifyDrinkingWater", "DrinkingWater"), id = "mycheckbox", @class = "toggle" })</td>
    </tr>
     }
     }
   else
   {
    <tr>
        <td colspan="@Html.ColumnCount(3)"><em>No Drinking Water data to verify.</em></td>
    </tr>
   }
    </tbody>
</table>


<hr />


@if (Model.Data.Count > 0)
{ 
    <script>

    $(document).ready(function () {
        makeDataTable('UnverifiedDrinkingWaterTable');
        $(function () {
            $('.toggle').change(function () {
                var self = $(this);
                var url = self.data('url');
                var id = self.attr('id');
                var value = self.prop(':checked');

                $.ajax({
                    url: url,
                    data: { id: id },
                    type: 'POST',
                    success: function (result) {
                        alert(response)
                    }

                });
            });

        });
    });

    </script>
}

生成的HTML:

<tr data-record-id="3" role="row" class="odd">
        <td>5</td>
        <td>Location</td>
        <td>1</td>
        <td>3/31/1997</td>
        <td>18:00:00</td>
        <td>YY</td>
        <td>Y</td>
        <td></td>
        <td><input class="toggle" data-url="/FP/DrinkingWater/VerifyDrinkingWater" data-val="true" data-val-required="The Verified field is required." id="mycheckbox" name="log.Verified" type="checkbox" value="true"><input name="log.Verified" type="hidden" value="false"></td>
    </tr>

data-record-id在数据库中的那些相匹配。

文章来源: ASP.NET MVC 5 POST checkboxfor to controller with onclick using Ajax