如果要在ASP.NET MVC 5中覆盖数据库行,如何向用户显示弹出窗口或警告 [英] How to show a pop up or warning to user if the DB Row is going to be overwritten in ASP.NET MVC 5

查看:68
本文介绍了如果要在ASP.NET MVC 5中覆盖数据库行,如何向用户显示弹出窗口或警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要求:我有一个推荐表格,用户可以在其中填写详细信息以申请工作.现在,按照我的要求,如果用户想重新申请同一份工作,他可以​​多次申请(为此感到高兴).因此,如果我检测到该用户之前已经申请过该工作,则需要更新旧的推荐请求,否则请创建一个新请求.

Requirement: I have a referral form, where user can fill in the details to apply for a job. Now, As per my requirement, if a user wants to reapply for the same job, he can do so, multiple number of times (humor me on this). So, If I detect that user has already applied for the job before then I need to update the old referral request, if not then create a new request.

当前行为:我已经成功编写了覆盖现有值的逻辑(如果用户之前已经申请过).但是,如果我在更新简历,日期时间和其他字段之前检测到用户已经申请了此工作,则想显示一个弹出窗口或一些确认信息.一旦用户说是",那么只有我想覆盖这些值.

Current Behaviour: I have successfully written the logic to overwrite the existing value (if user had already applied before). But I want to show a pop up or some confirmation, if I detect that the user has already applied to this job, before updating resume and datetime and other fields. And once user says Yes, then only I want to overwrite the values.

问题:我不知道如何实现上述目标.因为一旦请求转到后端控制器操作,那么只有我才能检测到这是新的东西,或者这是已经存在的东西,需要重写,并且需要显示POP UP.

Issue: I have no clue how to achieve above. Because once the request goes to backend controller action then only I can detect that this is something new or this is something which is already existing and needs to be overwritten and a POP UP needs to be shown.

查看:

@model Bridge.ViewModels.ReferralViewModel
@using (Html.BeginForm())
{
    <div class="form-horizontal">
        <h4>Job Request</h4>
        <div class="form-group">
            @Html.LabelFor(model => model.CompanyId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(m => m.CompanyId, Model.Companies, "Please Select", new { @class = "form-control", data_url = Url.Action("ListOfCoverLetterByCompanyId", "Referral") })
            </div>
        </div>
       @* SOME FIELDS REMOVED FOR BREVITY*@
        <div class="form-group">
            @Html.LabelFor(model => model.ResumeId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(m => m.ResumeId, Model.Resumes, new { @class = "form-control" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.CoverLetterId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(m => m.CoverLetterId, Model.CoverLetters, "Please select", new { @class = "form-control" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

控制器操作

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ReferralViewModel viewModel)
{
    var candidateId = User.Identity.GetUserId();
    var referral = _context.Referrals.Where(r => (r.CandidateId == candidateId) && (r.CompanyId == viewModel.CompanyId)).SingleOrDefault();
    if (referral != null)
    {
        // if already existing then show a confirmation/warning before updating
        referral.ResumeId = viewModel.ResumeId;
        referral.CoverLetterId = viewModel.CoverLetterId;
        referral.dateTime = DateTime.Now;
    }
    else
    {
      // If new then add the entry
    }
    _context.SaveChanges();

    return RedirectToAction("ReferralCenter");
}

编辑

尝试1:

查看:

@section scripts {
        <script>
            $('form').submit(function () {
                var data = $('form').serialize();
                var url = '@Url.Action("CheckForExistingReferral")';
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    success(data)
                    {
                        debugger;
                        alert("hello");
                        // some logic
                    },
                    error()
                    {
                        debugger;
                    alert("error");
                     //some logic
                }
                });
            });     
        </script>
    }

AJAX操作:

[HttpPost]
public JsonResult CheckForExistingReferral(ReferralViewModel viewModel)
{
    bool hasPreviousRequest = false;
    var candidateId = User.Identity.GetUserId();
    var referral = _context.Referrals.Where(r => (r.CandidateId == candidateId) && (r.CompanyId == viewModel.CompanyId) && (r.SkillId == viewModel.SkillId) && (string.IsNullOrEmpty(r.ReferrerId))).SingleOrDefault();
    hasPreviousRequest = referral != null;
    return Json(new { hasPreviousRequest = hasPreviousRequest });

}

问题:

JSON函数的断点被命中,但是在它可以返回结果之前,我的实际表单POST方法断点被命中.我希望Form POST控制器操作等待AJAX​​调用返回.

Breakpoint at JSON Function gets hit, but before it can return the result, my Actual Form POST Method breakpoint gets hit. I want the Form POST controller action to wait for AJAX call return.

尝试2

查看

@section scripts {
    <script>
            var canSubmit = false;
            debugger;
            $('form').submit(function (e) {
                if (!canSubmit)
                    e.preventDefault();
                var data = $('form').serialize();
                var url = '@Url.Action("CheckForExistingReferral")';
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    success(response){
                        if (response.hasPreviousRequest)
                        {
                            if (confirm("You've already applied for this job. Apply again?")) {
                                canSubmit = true;
                                $('form').submit();
                            }
                        }
                        else {
                            canSubmit = true;
                            $('form').submit();
                        }
                    },
                    error(){
                       alert("error");
                    }
                }); 
            });
        </script>
    }

问题:对于单击,我的Json Action至少被命中3次.应该只打一次.

Issue: For single click, my Json Action gets hit atleast 3 times. It should be hit just once.

尝试3

为表单提供一个ID:

@using (Html.BeginForm("Create", "Referral", FormMethod.Post, new { id = "job-form" }))
{}

脚本:

@section scripts {
    <script>
            var canSubmit = false;
            debugger;
            $('#job-form').submit(function (e) {
                if (!canSubmit)
                    e.preventDefault();
                var data = $('#job-form').serialize();
                var url = '@Url.Action("CheckForExistingReferral")';
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: data,
                    success: function (response) {
                        if (response.hasPreviousRequest)
                        {
                            if (confirm("You've already applied for this job. Apply again?")) {
                                canSubmit = true;
                                $('#job-form').submit();
                            }
                        }
                        else {
                            canSubmit = true;
                            $('#job-form').submit();
                        }
                    },
                    error: function (){ 
                       alert("error");
                    }
                }); 
            });
        </script>
    }

问题:我一直看到循环弹出JS.

ISSUE: I keep on seeing the JS Pop up in a loop.

推荐答案

您基本上可以重复当前在POST操作中使用的检查,但是可以返回一个简单的JSON值:

You can basically repeat the check you use in the POST action currently, but return a simple JSON value instead:

public ActionResult CheckForExistingReferral(ReferralViewModel viewModel)
{
    bool hasPreviousRequest = false;

    var candidateId = User.Identity.GetUserId();
    var referral = _context.Referrals.Where(r => (r.CandidateId == candidateId) && (r.CompanyId == viewModel.CompanyId)).SingleOrDefault();

    hasPreviousRequest = referral != null;

    return Json(new { hasPreviousRequest = hasPreviousRequest }, JsonRequestBehavior.AllowGet);
}

您认为您将执行以下操作:

In your view, you'd do something like:

var data = $('form').serialize();
var url = '@Url.Action("CheckForExistingReferral")';

$.get(url, data)
    .done(function(response, status, jqxhr){
        if(response.hasPreviousRequest){
            // show alert?
        }
        else{
            // post form?
        }
    });

这是使用jQuery的 $ .get 帮助器,(通常)将其包装 $ .ajax 函数.序列化会将您的表单值进行URL编码,使其适合通过Ajax请求提交的格式,或者您如果愿意,可以手动构造JavaScript对象.

This is using jQuery's $.get helper, which (mostly) just wraps their $.ajax function. serialize will URL-encode your form values into a format suitable for submitting through the Ajax request, or you can manually construct a JavaScript object, if you prefer.

.done()函数处理成功的响应(任何状态码为200的响应).如果要处理错误/失败的请求,则可以添加一个 .fail()函数,如下所示:

The .done() function handles successful responses (anything with a 200 status code). If you want to handle bad/failed requests, you'd add a .fail() function, something like this:

$.get(url, data)
    .done(function(response, status, jqxhr){
    })
    .fail(function(jqxhr, status, error){
    });

错误将包含一个对象,该对象包含从服务器返回的错误详细信息.在两种情况下, jqxhr 是jQuery创建的 XMLHTTPRequest .

error will contain an object that contains the error details returned from the server. jqxhr, in both instances, is the XMLHTTPRequest created by jQuery.

当然,由于您现在要重复一段代码,因此您可能应该将此重复检查重构为帮助方法之类的东西,然后在两个操作中都将其替换.

Of course, since you'd now be repeating a chunk of code, you should probably refactor this duplicate check into something like a helper method, and then replace the check in both actions.

由于除非用户已确认重新提交(或者之前没有提交),否则您不希望允许提交表单,因此您需要阻止表单提交.这是一个示例:

Since you don't want to allow the form submission unless the user has confirmed the resubmission (or there wasn't a previous submission), you need to prevent the form submission. Here's an example:

// check variable - we'll update this in the handler below
var canSubmit = false;

$('form').on('submit', function(e){   
    // Have we checked for resubmissions yet, or has the user approved the resubmit?
    if(!canSubmit){
        e.preventDefault();

        var data = $('form').serialize();
        var url = '@Url.Action("CheckForExistingReferral")';

        $.get(url, data)
            .done(function(response, status, jqxhr){
                if(response.hasPreviousRequest){
                    // show alert?
                    if(confirm("You've already applied for this job. Apply again?")){
                        canSubmit = true;
                        // $('form').submit(); re-triggers the form submission. 
                        // Since the value is now true, the form submission occurs normally
                        $('form').submit();
                    }                       
                }
                else{
                    // post form?
                    canSubmit = true;
                    $('form').submit();
                }
            });
    }
});

这篇关于如果要在ASP.NET MVC 5中覆盖数据库行,如何向用户显示弹出窗口或警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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