ASP.NET [Route("api/dvds/search")] function does not get called - c#

I am making an ajax call to 'http://localhost:44315/api/listings/search', which can take in four parameters, such as title, releaseYear, director, and rating, but everytime I call the route, when debugging, the function Search() never gets called. I have also tried postman, but it seems like whatever tool I use, it just hangs and fails to reach the path. If you know another way of setting this route, I would like to know.
Here is my ListingsAPIController.cs
public class ListingsAPIController : ApiController
{
[Route("api/dvds/search")]
[AcceptVerbs("GET")]
public IHttpActionResult Search(string title, int? releaseYear, string director,
string rating)
{
var repo = DvdRepositoryFactory.GetRepository();
try
{
var parameters = new ListingSearchParameters()
{
Title = title,
ReleaseYear = releaseYear,
Director = director,
Rating = rating
};
var result = repo.Search(parameters);
return Ok(result);
}
catch (Exception ex)
{
return BadRequest(ex.Message);
}
}
}
Views/Listings/Search.cshtml:
#section Scripts
{
<script>
$(document).ready(function () {
$("#searchForm").submit(function (e) {
search();
return false;
});
});
function search() {
var params;
params = 'title=' + $('#title').val() + '&releaseYear=' + $('#releaseYear').val() + '&director=' +
$('#director').val() + '&rating=' + $('#rating').val();
$.ajax({
type: 'GET',
url: 'http://localhost:44315/api/dvds/search?' + params,
success: function (results) {
console.log("search");
$('#searchResults').empty();
$.each(results, function (index, dvd) {
var html = '<div class="col-xs-8 col-sm-4 col-md-4">' +
'<div class="card" style="border:2px solid #0094ff; width: 20rem; border-radius: 5px; ">' +
'<div class="pl-3 pt-1 text-center">' +
'<h4 class="card-title text-primary">' + dvd.Title + '</h4>' +
'<p class="recentListing">' + dvd.ReleaseYear + '</p>' +
'<p class="recentListing">' + dvd.Director + '</p>' +
'<p class="recentListing">' + dvd.Rating + '</p>' +
'<p class="recentListing">' + dvd.Notes + '</p>' +
'</div>';
$('#searchResults').append(html.toString());
});
},
error: function () {
alert('Error performing search, try again later!')
},
done: function () {
alert('Search AJAX complete')
}
});
}
</script>
}
I have tried renaming the route from listings to dvds, but still getting error.
UPDATE: What I have learned is that Visual Studio 2019 has forced projects to use the "Configure for HTTPS" option when changing Authentication to "Individual User Accounts". HTTP used to be the default for older versions.

You call http while your api at https so in your search page call https
url: 'https://localhost:44315/api/dvds/search?'
or just delete the base URL :
url: '/api/dvds/search?'
Check your query maybe you have an error in SQL

Related

Print value one by one from controller in asp.net MVC, when controller is called from ajax

I have a AJAX call for controller as below,
function print(response, endpoint) {
$(".tt").append("<tr><td>" + JSON.stringify(response[0], null) + "</td><td>" + JSON.stringify(response[1], null) + "</td><td>" + JSON.stringify(response[2], null) + "</td><td>" + JSON.stringify(response[3], null) + "</td><td>" + JSON.stringify(endpoint, null) + "</td></tr>");
}
$(".submit").click(function () {
var env = $("#env").find(":selected").text();
var region = $("#region").find(":selected").text();
var country = $("#country").find(":selected").text()
var folderPath = $.trim($('#folderPath').val());
var ajaxRequest = $.ajax({
contentType: "application/json ;charset=utf-8",
type: "GET",
async: false,
url: "/Home/GetmyModel" + "?selcetion=" + env + "&region=" + region + "&country=" + country + "&folderpath=" + folderPath,
success: function (response) {
if (response != null) {
//print(response, endpoints[i]);
}
},
error: function (exception) {
},
complete: function (data) {
}
});
My controller goes like this
public void GetmyModel(string selcetion, string region, string country, string folderpath)
{
foreach (var item in System.IO.File.ReadLines(folderpath))
{
//do some work with return value as list<string>
//show list<string> in table in view using either print method of JS or by another way
}
}
Everything works fine if i send complete response back by making return type as JsonResult. However i am not understanding how can i print each item.

Bad request While Sending multipart/form-data to mvc controller using dynamically created HTML form

I have read all related question on all the portals since 2 days but i aint able to fix this issue , please look into this.
I have created a dynamic html form :
var jsprintId = "#Model.print.Id";
function DisplayIfExists(jsimageType, reqdiv) {
var d = document.getElementById(reqdiv);
$.ajax({
type: 'GET',
data: { printId: jsprintId, imageType: jsimageType },
url: '/Prints/'+jsprintId+'/Image/'+jsimageType,
success: function (response) {
if (response == "NoImage") {
d.innerHTML = "<form method='POST' action='http://localhost:5000/Prints/"+jsprintId+"/edit/UploadPrintImage' enctype='multipart/form-data' id='frmUploadIconImage'>" +
"<h1 style='text-transform:capitalize;margin-left:15px'>" + jsimageType + " Image</h1>" +
"<input type='hidden' name='printId' value='"+jsprintId+"'>"+
"<div class='row' style='margin: 1em -1em;'>" +
"<div class='col-md-10' style= 'padding: 0; overflow:hidden;'>" +
"<label type= 'text' class='form-control txtbox' id= 'lbl_svg_icon' style= 'margin-left:27px;height:34px'> Icon Image (SVG)</label>" +
"</div>" +
"<label class='btn btn-primary' for='svg_file_icon'>Browse<input type='file' name='svg_file_icon' id='svg_file_icon' style='display:none'/></label>" +
"</div>" +
"<div class='row text-center'>" +
"<input class='btn btn-primary' type='submit' value='Upload' id='btnUploadSubmit'/>" +
"</div>"
"</form>";
}
else {
d.innerHTML = "<img src='" + response + "' style='width:150px'> "
}
}
})
}
and my function for Sending this post request is :
$(function(){
$("#tabs-test").on('submit', '#frmUploadIconImage', function (form) {
form.preventDefault();
var data = new FormData(this);
if (iconImageValid) {
for (var key of data.entries()) {
console.log(key[0] + ', ' + key[1]);
}
$.ajax({
url: '#Html.Raw(Url.Action("UploadPrintImage", "Prints"))',
data: data,
method: 'POST',
cache: false,
contentType: false,
processData: false,
success: function (response) {
DisplayIfExists(jsimageType, "tabs-test");
},
error: function (error) {
console.log('your problem is ' + error.statusText);
console.log(error);
}
});
}
else {
alert("You can upload only SVG files");
$("#lbl_svg_icon").parent().addClass("has-error");
$("#lbl_svg_icon").text("SVG File");
return false;
}
});
});
the error I get is a bad request , my controller action is :
[HttpPost("Prints/{printId}/edit/UploadPrintImage")]
[Consumes("multipart/form-data")]
public async Task<ActionResult> UploadPrintImage(IFormCollection form)
{
//my code
}
it gives me the same error with all the argument type that i define i have tried the following :
public async Task<ActionResult> UploadPrintImage(FormCollection form);
public async Task<ActionResult> UploadPrintImage(HttpContext form);
public async Task<ActionResult> UploadPrintImage(HttpRequest form);
public async Task<ActionResult> UploadPrintImage(string printId, IFormfile file);
and all possible combinations but nothing works all it gives is a 400 BAD request.
following is my request screenshot:
the same code works when i have a hardcoded html form but not with dynamically created html form.
looking forward to a working solution. Thanks

jQuery Select2 ajax data source not triggered / called

I'm trying to bind my Select2 dropdown list to an MVC (v5.2.3) controller of my application.
I've pretty much copied the code from the demo:
<select id="select-ticket-test" class="duplicate-post-select" style="width: 100%;" placeholder="Select ticket">
<option></option>
<option value="3620194" selected="selected">select2/select2</option>
</select>
#section Scripts {
<script type="text/javascript">
function formatTicket(ticket) {
if (ticket.loading) {
return ticket.text;
}
var markup = "<div class='select2-result-repository clearfix'>" +
"<div class='select2-result-repository__avatar'><img src='" + ticket.owner.avatar_url + "' /></div>" +
"<div class='select2-result-repository__meta'>" +
"<div class='select2-result-repository__title'>" + ticket.full_name + "</div>";
if (ticket.description) {
markup += "<div class='select2-result-repository__description'>" + ticket.description + "</div>";
}
markup += "<div class='select2-result-repository__statistics'>" +
"<div class='select2-result-repository__forks'><i class='fa fa-flash'></i> " + ticket.forks_count + " Forks</div>" +
"<div class='select2-result-repository__stargazers'><i class='fa fa-star'></i> " + ticket.stargazers_count + " Stars</div>" +
"<div class='select2-result-repository__watchers'><i class='fa fa-eye'></i> " + ticket.watchers_count + " Watchers</div>" +
"</div>" +
"</div></div>";
return markup;
}
function formatTicketSelection(ticket) {
return ticket.Id || ticket.Subject;
}
$("#select-ticket-test").select2({
placeholder: "Select a state",
allowClear: true,
ajax: {
url: "#Url.Action("GetAjaxAsync")",
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term,
pageSize: params.page,
pageNum: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: false
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatTicket,
templateSelection: formatTicketSelection
});
</script>
}
public async Task<ActionResult> GetAjaxAsync(string searchTerm, int pageSize, int pageNum)
{
long number = Convert.ToInt64(searchTerm.Replace("T", null));
var posts = await UnitOfWork.SupportPosts.Where(x => x.Number == number).ToListAsync();
var json = new
{
Results = posts.Select(x => new
{
x.Id,
x.NumberName
}),
Total = posts.Count
};
return Json(json, JsonRequestBehavior.AllowGet);
}
What I've noticed is, that the placeholder isn't even shown. The Select2 is initialized (as in "not a "real" dropdown anymore"), but no placeholder is shown. And when typing into the textbox, no call is even made to my controller.
There are no JavaScript errors in the console either.

Why does the data come back as undefined?

I'm not understanding why the data is coming back as undefined. It knows there is something there but the value is not being shown. Am I forgetting to do something in the main function? Thanks in advance to whom may solve my dilemma.
Here is the current output I'm getting:
Here is what I need the output to render:
Here is the code for my employee.js:
$(function() {
ajaxCall("Get", "api/employees", "")
.done(function (data) {
buildTable(data);
})
.fail(function (jqXHR, textStatus, errorThrown) {
errorRoutine(jqXHR);
}); // ajaxCall
});
// build initial table
function buildTable(data) {
$("#main").empty();
var bg = false;
employees = data; // copy to global var
div = $("<div id=\"employee\" data-toggle=\"modal\"data-target=\"#myModal\" class=\"row trWhite\">");
div.html("<div class=\"col-lg-12\" id=\"id0\">...Click Here to add</div>");
div.appendTo($("#main"));
$.each(data,function(emp){
var cls = "rowWhite";
bg ? cls = "rowWhite" : cls = "rowLightGray";
bg = !bg;
div = $("<div id=\"" + emp.Id + "\" data-toggle=\"modal\" data-target=\"#myModal\" class=\"row col-lg-12" + cls + "\">");
var empId = emp.Id;
div.html(
"<div class=\"col-xs-4\" id=\"employeetitle" + empId + "\">" + emp.Title + "</div>" +
"<div class=\"col-xs-4\" id=\"employeefname" + empId + "\">" + emp.Firstname + "</div>" +
"<div class=\"col-xs-4\" id=\"emplastname" + empId + "\">" + emp.Lastname + "</div>"
);
div.appendTo($("#main"));
}); // each
} // buildTable
function ajaxCall(type, url, data) {
return $.ajax({// return the promise that '$.ajax' returns
type: type,
url: url,
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true
});
}
Here is my Controller method code:
// GET api/<controller>
[Route("api/employees")]
public IHttpActionResult Get()
{
try
{
EmployeeViewModel emp = new EmployeeViewModel();
List<EmployeeViewModel> allEmployees = emp.GetAll();
return Ok(allEmployees);
}
catch(Exception ex)
{
return BadRequest("Retrieve failed - " + ex.Message);
}
}
The first parameter of the callback is the index, the value is in the second parameter:
$.each(data,function(index, emp){

ReferenceError: getMessage not defined

I am building a messaging area similar to facebook and I am using ajax with jquery and a asmx web service to serve the html to the client. My li click event works when the content is first loaded on page load using c#, but when ajax runs and refreshes the content from the web service the li event doesn't work anymore.
This an example of the html that is returned from the web service
<ol class="messagesrow" id="messages">
<li id="2345">
<div>Test Element</div>
</li>
</ol>
Web service markup
[WebMethod]
public string GetMessagesByObject(string id, string objectid, string userid, string timezone)
{
string output = string.Empty;
try
{
StringBuilder str = new StringBuilder();
DataSet results = results from store procedure
str.Append("<ol class=\"messagesrow\" id=\"messages\">");
for (int i = 0; i < results.Tables[0].Rows.Count; i++)
{
DataRow row = results.Tables[0].Rows[i];
DateTime date = Convert.ToDateTime(row["CreateDate"].ToString()).AddHours(Convert.ToDouble(timezone));
if (!TDG.Common.CheckStringForEmpty(row["ParentMessageID"].ToString()))
{
str.Append("<li id=\"" + row["ParentMessageID"].ToString() + "\">");
}
else
{
str.Append("<li id=\"" + row["MessageID"].ToString() + "\">");
}
str.Append("<div style=\"width:100%; cursor:pointer;\">");
str.Append("<div style=\"float:left; width:25%;\">");
if (!TDG.Common.CheckStringForEmpty(row["ImageID"].ToString()))
{
str.Append("<img src=\"/Resources/getThumbnailImage.ashx?w=48&h=48&id=" + row["ImageID"].ToString() + "\" alt=\"View Profile\" />");
}
else
{
str.Append("<img src=\"/images/noProfileImage.gif\" alt=\"View Profile\" />");
}
str.Append("</div>");
str.Append("<div style=\"float:left; width:75%; padding-top:4px;\">");
str.Append("<strong>" + row["WholeName"].ToString() + "</strong>");
str.Append("<br />");
if (row["BodyMessage"].ToString().Length < 35)
{
str.Append("<span class=\"smallText\">" + row["BodyMessage"].ToString() + "</span>");
}
else
{
str.Append("<span class=\"smallText\">" + row["BodyMessage"].ToString().Substring(0, 35) + "</span>");
}
str.Append("<br /><span class=\"smallGreyText\">" + String.Format("{0:g}", date) + "</span>");
str.Append("</div>");
str.Append("</div>");
str.Append("</li>");
}
str.Append("</ol>");
output = str.ToString();
}
catch (Exception ex)
{
throw ex;
}
return output;
}
Jquery markup
$(document).ready(function () {
$("ol#messages li").click(function () {
var id = $(this).attr("id");
getMessage(id);
});
});
function getMessage(id) {
var timezone = $('#<%= hdfTimezone.ClientID %>').val()
var userid = $('#<%= hdfUserID.ClientID %>').val()
$.ajax({
type: "POST",
async: false,
dataType: "json",
contentType: "application/json; charset=utf-8",
url: "/Resources/MessageWebService.asmx/GetMessage",
data: "{'id':'" + id + "','timezone':'" + timezone + "','userid':'" + userid + "' }",
success: function (data) {
$('#<%= hdfMessageID.ClientID %>').val(id);
$('#<%= ltlMessages.ClientID %>').html(data.d);
},
error: function (data) {
showError(data.responseText);
}
});
}
Since your list items are dynamic, you should delegate the event from the ol.
$(document).ready(function () {
$("#messages").delegate("li","click",function () {
getMessage(this.id);
});
});
The error you are getting ReferenceError: getMessage not defined shouldn't happen with the given code.

Categories