Amble
Amble

Reputation: 227

Linking button to controller using jquery and ajax (url)

I'm trying to create a button that does a database lookup for a value in an MVC project. I'm a bit stuck after reading round so could do with some tips.

Actual cshmtl for Create

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

Actual code for 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 code in controller

[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);
        }

***** UPDATE *****

I think the code is now fine, we've tested some javascript alerts and they are pulling the correct field and data. The problem seems to be in the ajax call as it gets a 404 when trying to route through to the controller. Like this:

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

Upvotes: 0

Views: 1722

Answers (3)

Jamie Rees
Jamie Rees

Reputation: 8183

What I usually do is the following to get the ActionMethods URL in the JS code:

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

But as Hackerman mentioned, if your view belongs to that controller you can just do:

@Url.Action("GetData")

Upvotes: 2

Vijayanand Settin
Vijayanand Settin

Reputation: 1074

You need to use your Controller class name in place of YourControllerName, GetData is the action name, in your case.

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

returns the action url.

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

Try this:

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

Upvotes: -1

Hackerman
Hackerman

Reputation: 12305

If your view belong to the same controller you just need to change you code a little bit:

var url = 'GetData';

If you view is in another controller, then this should works:

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

Upvotes: 0

Related Questions