Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在ASP MVC中将用户输入的ID与数据库中存储的ID进行比较_C#_Asp.net Mvc_Razor - Fatal编程技术网

C# 如何在ASP MVC中将用户输入的ID与数据库中存储的ID进行比较

C# 如何在ASP MVC中将用户输入的ID与数据库中存储的ID进行比较,c#,asp.net-mvc,razor,C#,Asp.net Mvc,Razor,我有一个表单,允许用户创建一个新的供应商。我希望用户在文本框中输入供应商的ID,但在创建供应商之前,我需要确保该ID未被使用。如果该ID已获取,我希望出现一条消息,告诉用户该ID已获取,并禁用提交按钮,直到输入有效的ID 我有一个函数,可以从数据库中提取供应商ID,并根据数据库中已有的ID列表检查用户输入的ID。它根据是否使用用户输入的ID返回布尔值 我遇到的问题是,它不允许我在javascript中调用此函数。运行应用程序时,它告诉我JavaScript运行时错误:“IsIdTaken”未定义

我有一个表单,允许用户创建一个新的供应商。我希望用户在文本框中输入供应商的ID,但在创建供应商之前,我需要确保该ID未被使用。如果该ID已获取,我希望出现一条消息,告诉用户该ID已获取,并禁用提交按钮,直到输入有效的ID

我有一个函数,可以从数据库中提取供应商ID,并根据数据库中已有的ID列表检查用户输入的ID。它根据是否使用用户输入的ID返回布尔值

我遇到的问题是,它不允许我在javascript中调用此函数。运行应用程序时,它告诉我JavaScript运行时错误:“IsIdTaken”未定义。如何从javascript中调用函数?或者,如何从数据库中获取ID,以对照用户输入的ID进行检查

下面是我的代码:

@model EnterpriseServices.Vendor.Vendor

@{
    ViewBag.Title = "Add Vendor";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@functions {
    public static bool IsIdTaken(string userEnteredId)
    {
        bool isTaken = false;
        List<string> IDs = new List<string>();
        var vendors = EnterpriseServices.Vendor.VendorUtility.GetVendorIDandName();

        foreach (var v in vendors)
        {
            IDs.Add(v.Id);
        }

        if(IDs.Contains(userEnteredId))
        {
            isTaken = true;
        }

        return isTaken;
    }
}

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Create Vendor</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.Label("Vendor ID: ", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Id, new { htmlAttributes = new { @class = "form-control", id = "IdTextBox" } }) <label style="color:red" id="idTaken">This ID is already taken</label>
                @Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.Label("Name: ", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.Label("Notes: ", htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Notes, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Notes, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.Label("Is Active: ", htmlAttributes: new { @class = "control-label col-md-2"})
            <div class="col-md-10">
                @Html.CheckBoxFor(model => model.IsActive, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.IsActive, "", new { @class = "text-danger"})
            </div>
        </div>

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

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

<script type="text/javascript" src="jquery-2.1.4.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $('#idTaken').hide()
        $('#IdTextBox').focusout(function () {
            var textboxId = $('#IdTextBox').val($(this).val())
            if (textboxId != null)
            {
                //Check to see if the Vendor ID entered by the user is already being used
                if (IsIdTaken(textboxId.toString()))
                {
                    $('#idTaken').show()
                    $('#submitButton').disabled()
                }
                else
                {
                    $('#idTaken').hide()
                    $('#submitButton').enabled()
                }
            }
        })
    })
</script>

为什么不让数据库决定供应商的ID?如果您仍然想调用数据库,则需要使用ajax查询,我认为@functions仅在razor构建页面时被调用,并且在加载页面后将无法使用javascript调用。如果你在stackoverflow上搜索它,那么在你被发布之前会有很多例子

Razor在服务器端运行,Javascript在客户端运行。您不能在JavaScript中调用Razor函数,因为此时,服务器已不再参与。您需要使用AJAX向应用程序中的某个端点控制器操作发送id为的请求。然后,从该端点返回一点JSON,指示该值是否有效。然后可以使用JavaScript根据返回的JSON显示/隐藏错误消息。您还需要限制AJAX,以便只在输入某个字符阈值或用户完全移出字段后发送请求。

我会将所有供应商ID放在您的模型上,因此,如果您真的想在客户端调用它,您只需调用一次。我会将您的IsIdTaken方法定义为javascript方法

我能够像Chris Pratt建议的那样,使用AJAX实现这一点

我的JavaScript:

<script type="text/javascript">
    $(document).ready(function () {
        $('#idTaken').hide()
        $('#IdTextBox').focusout(function () {
            $.ajax({
                type: "POST",
                url: '@Url.Action("CheckId", "VendorUI")'+ '?id=' + $('#IdTextBox').val(),
                contentType: "application/json; charset=utf-8",
                success: function(data) {
                    if (String(data) == "true")
                    {
                        $('#idTaken').show()
                        $('#submitButton').hide()
                        $('#IdTextBox').focus()
                    }
                    else
                    {
                        $('#idTaken').hide()
                        $('#submitButton').show()
                    }
                },
                error: function () {
                    alert('AJAX FAILED');
                }
            });
        })
    })
</script>
我的控制器:

public JsonResult CheckId(string id)
        {
            bool isTaken = false;
            List<string> IDs = new List<string>();
            IList<LightweightVendor> vendors = VendorUtility.GetVendorIDandName();

            foreach (var v in vendors)
            {
                IDs.Add(v.Id);
            }

                if (IDs.Contains(id))
            {
                isTaken = true;
            }

            return Json(isTaken);
        }

必须进行ajax调用,传入id,然后进行数据库调用。这是一种有效的方法,但请注意,此时数据已过时。如果有多个用户同时填写此表单,则仍可能发生冲突。您仍然可以通过AJAX检查id,但至少这样,您可以将其缩小到只有人们在几秒钟内发布相同表单的实例。是的,您必须检查服务器端,无论哪种情况,都有可能。决定用业绩来换取缩短潜在时间。谢谢你,克里斯。我以前从未使用过AJAX,但现在我将对此进行研究。我很感谢你的帮助。我能够像Chris建议的那样使用AJAX实现这一点。我将在下面发布代码以供将来参考。