使用 jquery 和 ajax (url) 将按钮链接到控制器

Linking button to controller using jquery and ajax (url)

我正在尝试创建一个按钮,用于对 MVC 项目中的值执行数据库查找。看完一轮后我有点卡住了,所以可以做一些提示。

创建的实际 cshmtl

  odel OncologyRTA.Controllers.oncologyPatient

@{
    ViewBag.Title = "Create";
}

<h2>Add new patient</h2>


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

    <button type="button" name="button" value="find">Search</button>


    <div class="form-horizontal">
        <h4><font color="red"><strong>LIVE Dataset</strong></font></h4>
        <hr />
        @Html.ValidationSummary(true)

        <dl class="dl-horizontal">
            <dt>
                @Html.LabelFor(model => model.HospitalID, new { @class = "control-label col-md-2" })
            </dt>

            <dd>
                @Html.TextBoxFor(model => model.HospitalID, new { onkeyup = "InputToUpper(this);"})
                @Html.ValidationMessageFor(model => model.HospitalID)
            </dd>

            <dt>
                @Html.LabelFor(model => model.NHS_No_, "NHS No.", new { @class = "control-label col-md-2" })
            </dt>

            <dd>
                @Html.EditorFor(model => model.NHS_No_)
                @Html.ValidationMessageFor(model => model.NHS_No_)
            </dd>

            <dt>
                @Html.LabelFor(model => model.Forename, new { @class = "control-label col-md-2" })
            </dt>

            <dd>
                @Html.TextBoxFor(model => model.Forename, new { onkeyup = "InputToUpper(this);", Name="Forename"})
                @Html.ValidationMessageFor(model => model.Forename)
            </dd>

            <dt>
                @Html.LabelFor(model => model.Surname, new { @class = "control-label col-md-2" })
            </dt>

            <dd>
                @Html.TextBoxFor(model => model.Surname, new { onkeyup = "InputToUpper(this);" })
                @Html.ValidationMessageFor(model => model.Surname)
            </dd>

            <dt>
                @Html.LabelFor(model => model.DOB, new { @class = "control-label col-md-2" })
            </dt>

            <dd>
                @Html.TextBoxFor(model => model.DOB, new { @Value = "dd/MM/yyyy" })
                @Html.ValidationMessageFor(model => model.DOB)
            </dd>

            <dt>
                @Html.LabelFor(model => model.Active, new { @class = "control-label col-md-2" })
            </dt>

            <dd>
                @Html.EditorFor(model => model.Active)
                @Html.ValidationMessageFor(model => model.Active)
            </dd>

            <dt>
                @Html.LabelFor(model => model.Deceased, new { @class = "control-label col-md-2" })
            </dt>

            <dd>
                @Html.EditorFor(model => model.Deceased)
                @Html.ValidationMessageFor(model => model.Deceased)
            </dd>

        </dl>



        <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>
}


<script>
    function InputToUpper(obj) {
        if (obj.value != "") {
            obj.value = obj.value.toUpperCase();
        }
    }
</script>

<script>
    $("button[name='button']").click(function (event) {
        event.preventDefault();
        var uquery = $('#HospitalID').val();
        var url = '@Url.Action("GetData")';
        var data = { value: uquery }
        $.ajax({
            url: url,
            data: data,
            success: function (data) {
                $('#Forename').val(data.HospitalID);
            }
        });
    })
</script>



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

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

class

的实际代码
>  public class Lkup
>     {
>         public string HospitalID { get; set; }
>         public string NHS_No_ { get; set; }
>         public string Forename { get; set; }
>         public string Surname { get; set; }
>         public System.DateTime DOB { get; set; }
>     }

控制器中的 HttpGet 代码

[HttpGet]
        public JsonResult GetData(string value)
        {
            var result = new Lkup();

            string connect = "Server=server\instance;Database=SQLtable;Trusted_Connection=True";
            string query = "select * from table1 where pkey =" +value;

            using (SqlConnection sql1 = new SqlConnection(connect))
            {
            sql1.Open();
            SqlCommand cmd = new SqlCommand(query);
            SqlDataReader rdr = cmd.ExecuteReader();
            {       if (rdr != null)
                    {
                        while (rdr.Read())
                        {
                            result.HospitalID = "column1";
                            result.Forename = "column2";
                            result.Surname = "colum3";
                        }
                    }
            rdr.Close();
            }
            sql1.Close();
            }

            return Json(result, JsonRequestBehavior.AllowGet);
        }

***** 更新 *****

我认为代码现在没问题,我们已经测试了一些 javascript 警报,它们正在提取正确的字段和数据。问题似乎出在 ajax 调用中,因为它在尝试路由到控制器时收到 404。像这样:

GET http://localhost:59845/oncologyPatientsController/GetData?id=1234567 404 (Not Found)
send @ jquery-1.10.2.min.js:23
x.extend.ajax @ jquery-1.10.2.min.js:23
(anonymous function) @ Create:157
x.event.dispatch @ jquery-1.10.2.min.js:22
v.handle @ jquery-1.10.2.min.js:22

如果您的视图属于同一个控制器,您只需稍微更改一下代码:

var url = 'GetData';

如果您的视图在另一个控制器中,那么这应该有效:

var url = '<%=ResolveUrl("~/YouControllerName/GetData")%>';

我通常做的是如下获取JS代码中的ActionMethodsURL:

<button type="button" value="find">Find</button>
<script>
    $("button").click(function(event)
    {
        event.preventDefault();
        var uquery = $('HID').val();
        var url = '@Url.Action("GetData","ControllerName")';
        var data = { value: uquery }
        $.ajax({
            url: url,
            data: data,
            success : function(data) 
            {
                $('HID').val(data.Value1);
            }
        });})

但是正如 Hackerman 提到的,如果您的视图属于该控制器,您可以这样做:

@Url.Action("GetData")

您需要使用控制器 class 名称代替 YourControllerName,在您的情况下,GetData 是操作名称。

@Url.Action("actionName", "controllerName") 

returns 动作 url.

e.g:   
var url = '@Url.Action("GetData", "YourControllerName")';

试试这个:

    <script>
>     $("button[name='button']").click(function (event) {
>         event.preventDefault();
>         var uquery = $('#HospitalID').val();
>         var url = '@Url.Action("GetData")';
>         var data = { value: uquery }
>         $.ajax({
>             url: url,
>             data: data,
>             success: function (result) {
>                 $('#Forename').val(result.hid);
>             }
>         });
>     }) </script>