Je suis en train de créer un bouton qui effectue une recherche de base de données pour une valeur dans un projet MVC. Je suis un peu coincé après avoir lu la ronde, donc je pourrais faire quelques conseils.Liaison du bouton au contrôleur à l'aide de jquery et ajax (url)
cshmtl réel pour créer
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")
}
code réel pour la classe
> 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 dans le contrôleur
[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);
}
***** ***** MISE À JOUR
Je pense que le code est maintenant fin e, nous avons testé quelques alertes javascript et ils tirent le bon champ et les données. Le problème semble être dans l'appel ajax car il obtient un 404 en essayant de passer par le contrôleur. Comme ceci:
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
La ligne 'chaîne de requête = « SELECT val.1, val.2, val.3, val.4 DE [SQL1 \\ INSTANCE] .dB.dbo .tbl1 AS L INNER JOIN [SQL1 \\ INSTANCE] .dB.dbo.SID AS S ON 1.ui = 2.ui O val val.1 = "+ value;' est mûr pour SQL Injection, un sérieux problème de sécurité. Voir http://www.troyhunt.com/2010/05/owasp-top-10-for-net-developers-part-1.html comme point de départ. –
Merci. J'essaie juste d'obtenir la fonctionnalité d'abord puis je vais durcir si nécessaire. – Amble
Qu'est-ce qui ne fonctionne pas? Et pourquoi ajoutez-vous 'new {Name =" HospitalID "}' etc? - la valeur de l'attribut 'name' est déjà' HospitalID'. Et '$ ('Prénom'). Val (data.HospitalID);' ne fera rien - il aurait besoin d'être '$ ('# Prénom'). Val (data.HospitalID);' –