I am just starting out on learning Razor. I have worked my way through 8 hours of a paid video tutorial and now I am attempting to develop a real world application with a lot of googling and side reading.
I have read many similar postings and tried many of the ideas but I am just banging my head against the wall. This issue arises from attempting to create cascading drop downs (select client, update drop down list of contacts at client) I have stripped out all the EF code and just gone back to a hand coded sample list of contacts. I am not even attempting to rebuild the select list for the contact drop down in this example - I would just be happy if the alert message would display a result instead of "undefined"
Here is the JQuery code at the bottom of the razor page:
@section Scripts
{
<script type="text/javascript">
$(document).ready
(
function ()
{
$('#TblTrials_ClientId').change
(
function ()
{
$.getJSON
(
"?handler=Contacts", function (result)
{
$.each(result, function (i, item)
{
alert(item.contactname);
});
}
);
}
);
}
);
</script>
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
and here is the "OnGetContacts" handler in the corresponding cs pagemodel
public JsonResult OnGetContacts()
{
List<clientcontact> clientcontacts = new List<clientcontact>{
new clientcontact{ClientContactId = 1, ContactName = "Scott"},
new clientcontact{ClientContactId = 2, ContactName = "Bill"}
};
JsonResult jsn = new JsonResult(clientcontacts);
return jsn;
}
I have breakpointed just before the "return jsn" and jsn is a collection of two entries so the handler is definitely being called. I am concerned that jsn looks more like the clientcontacts class rather than a JSON string but this probably down to my ignorance at this stage.
Here is my definition of the clientcontacts class
namespace TrialManagementSystem.Models
{
public partial class clientcontact
{
public int ClientContactId { get; set; }
public string ContactName { get; set; }
}
}
I have tried a number of ideas such as item.ContactName instead of item.contactname and result[i].ContactName and many other permutations
I would be very, very grateful for any suggestions.
Many thanks Tony
You just need to change your code:
alert(item.contactname);
to
alert(item.contactName);