trying to implement a search in .net MVC - c#

I am having a tough time figuring out how to do this. I have added a search box to the main page of my site. The site has various products you can buy divided into categories. When you click one of the categories(for instance Candles and Scents), it takes you to /Home/Products/candles-scents. Now I have created new methods in my controller and model which correctly do the search. My search function is basically duplicating my "product categories" function, only the sql query is modified. So I want the site to go to the products page again, just like for a specific category: /Home/Products/"search". I'm not sure if I should wrap my search box in a form or if there is a better way. Right now I am trying jquery ajax, but of course the page is not getting redirected.
Here is my search box html:
<input type="text" class="search" placeholder="search" onfocus="this.placeholder = ''" onblur="this.placeholder = 'search'"/>
And here is my jquery:
$(".search").keypress(function (event) {
var searchString = $(this).val();
console.log(searchString);
console.log("blah");
if (event.which == 13) {
$.ajax({
url: '#Url.Action("_search", "Home")',
data: {
search: searchString
}
})
}
});
And here is the _search function in the controller:
public ActionResult _search(string search)
{
// get the model
List<ProductModel> m = new List<ProductModel>();
m = ProductsModel.getProductsBySearch(search);
return View(m);
}
Then that function simply calls runs the sql query and returns a list of appropriate ProductModel's. I have the backend stuff figured out. I am just not sure how to correctly call my search from the front end.

Seems like you don't want Ajax here if you are returning a complete view.
Consider this javascript to do the redirection without a form:
$(".search").keypress(function (event) {
var searchString = $(this).val();
console.log(searchString);
console.log("blah");
if (event.which == 13) {
var searchUrl = '#Url.Action("_search", "Home")';
searchUrl += "/" + searchString;
window.location.href = searchUrl;
} // end if
});
Or, using a forms approach
<script type="text/javascript">
$(".search").keypress(function (event) {
var searchString = $(this).val();
console.log(searchString);
console.log("blah");
if (event.which == 13) {
$("#search-form").submit();
} // end if
});
</script>
<form id="search-form" method="post" action="#Url.Action("_search", "Home")">
<input type="text" class="search" name="search" placeholder="search" onfocus="this.placeholder = ''" onblur="this.placeholder = 'search'"/>
<input type="submit" value="Go" name="submit" />
</form>
The important piece I added was the name="search" attribute to your input. This tells the default MVC ModelBinder to find the HTML input element with a name matching your controller's action parameter (missing in your source).

You can use success function to prevent a page reload
$(".search").keyup(function (e) {
var searchString = $(this).val();
if (e.which == 13) {
$.ajax({
type: "POST",
url: '#Url.Action("_search", "Home")',
data: {
search: searchString
},
success: function () {
// do something here, like replace the html
}
});
}
});
One tip from conventions, use your action name like this
public ActionResult Search(string search)

Related

ASP.NET Core 6 & JsonResult

I have an application which searches for recording and play it. The application is running on .NET 6.0. I can display recording list in table and has play button as well.
Now I need to play recording & get text of that recording in same view/page when user click on play button in list. Below is my method which returns recording text. I need to stream text if recording size large. I can get recording text but not sure how it will display to page/view. My view model does not have this recording text field.
How can I achieve this?
[HttpPost]
public ActionResult GetRrcording(string recKey)
{
GetRecordingPath obj = new GetRecordingPath();
string Path = obj.GetPath(recKey);
SpeechRecognisation s = new SpeechRecognisation();
string recData = s.GetData(Path);
RecordingText rec = new RecordingText();
var jsonString = JsonConvert.SerializeObject(rec);
return Ok(jsonString);
}
I have a suggestion like below:
You can create a new model to have this recording text field, and in the view use a <span> and ajax to show the value.
For example:
[HttpPost]
public JsonResult AjaxMethod(string name)
{
NewModel model = new NewModel
{
RecordingText = name,
};
return Json(model);
}
View:
<input type="text" id="txtName" />
<input type="button" id="btnGet" value="submit" />
<sapn id="responseText"></sapn>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnGet").click(function () {
$.ajax({
type: "POST",
url: "/Json/AjaxMethod",
data: { "name": $("#txtName").val() },
success: function (response) {
$("#responseText").html(response.recordingText);
}
});
});
});
</script>
Or
Not create a new model, just return jsonString
return Json(jsonString);
And in the view:
$("#responseText").html(response);
result:

Populate a textbox based on selected value from dropdown using ASP.NET Core MVC

I am using ASP.NET Core 3.1 MVC to create a page with a form. The form has a dropdown and a textbox. The dropdown is populated with values from the database. The textbox will populate with a value from the same table and the dropdown, based on the selected dropdown value. My goal is to call a function from my controller inside of my view, is that possible?
My cshtml file:
<form method="post" asp-controller="Index" asp-action="Index" role="form">
<div class="form-group">
<select id="fileName" asp-items="#(new SelectList(ViewBag.message, "ID", "fileName"))" onchange="getUploadedFile()"></select>
<input />
</div>
</form>
My Model
public class myFiles
{
public int ID {get; set;}
public string fileName {get; set;}
public string uploadedFile {get; set;}
}
My controller has a function named GetUploadedFile() which runs a query to the database that returns the file name based on the ID. I originally thought I could reference the GetUploadedFile through my view(cshtml file) by adding the onchange handler and setting it as onchange="GetUploadedFile()". I have also tried to do an ajax call to get the UploadedFile.
My goal is to call a function from my controller inside of my view, is that possible?
Do you mean you want to add the myfiles' uploadfile value according to the dropdownlist selected value in the onchange getUploadedFile jquery method? If this is your requirement, I suggest you could try to use ajax to achieve your requirement.
You could write the ajax to post request to the mvc action, then you could get the value and set the result to the textbox.
Details, you could refer to below codes:
<form method="post" asp-controller="home" asp-action="Index" role="form">
<div class="form-group">
<input id="uploadedFile" type="text" class="form-control" />
<select id="fileName" asp-items="#(new SelectList(ViewBag.message, "ID", "fileName"))" onchange="getUploadedFile(this)"></select>
</div>
</form>
<script>
function getUploadedFile(Sle) {
$.ajax({
url: "/Home/GetUploadfileName",
data: { "FileID": Sle.value} ,
type: "Post",
dataType: "text",
success: function (data) {
console.log(data);
$("#uploadedFile").val(data);
},
error: function (data) {
alert(data);
}
});
}
</script>
Action method:
private List<myFiles> myfiletestdata = new List<myFiles>() {
new myFiles(){ ID=1, fileName="test1", uploadedFile="testuploadfile" },
new myFiles(){ ID=2, fileName="test2", uploadedFile="testuploadfile2" },
new myFiles(){ ID=3, fileName="test3", uploadedFile="testuploadfile3" },
};
[HttpPost]
public IActionResult GetUploadfileName(int FileID) {
//get the filename result accoding to ID
var result = myfiletestdata.Where(x=>x.ID== FileID).First();
return Ok(result.uploadedFile);
}
Result:
If I understand correctly, you just want to get the file name from the database when a value from the dropdown is selected.
What errors did you get when you tried the ajax call??
In your cshtml file, you can have something like this:
<script>
function getUploadedFile() {
var id = $('#fileName option:selected').val();
$.getJSON('/ControllerName/GetUploadedFile', { id: id }, function (result) {
var file = result.fileName;
.... do whatever with the result
to set value of the textbox:
$('#textBoxId').text(file);
});
}
</script>
Instead of getJSON, you could use ajax:
<script>
function getUploadedFile() {
var id = $('#fileName option:selected').val();
$.ajax({
url: 'ControllerName/GetUploadedFile',
type: 'GET',
dataType: 'json',
data: {
'id': id
}
})
.done(function (result) {
if (!result.errored) {
var file = result.fileName;
}
else {
}
});
}
</script>
Then in your controller, if you are not submitting the form and just want to update the value of the textbox, then it can just be:
[HttpGet]
public async Task<IActionResult> GetUploadedFile(int id)
{
Sample code:
var file = await GetFileFromDb(id);
return Json(new { fileName = file });
}
Also, you should consider using ViewModels instead of ViewBag.

MVC5 Fail to GET php api using ajax after submit a form and redirect

I'm using MVC5. Want to submit a form and then pass all input value to a php api.
If I submit my input using form,passing value to php api and do not redirect to other action , it will work.
But if I redirect to index after submit form , it will fail.
I have to REDIRECT to index after submit , but don't know how to fix.
I've tested my api and it works.
This is html View:
<form id="registerForm" method="post" action="~/OverTime/Add">
<input type="text" class="form-control" id="OverTime_Description" name="OverTime_Description" />
<input class="form-control" id="DateStart" name="DateStart" type="text"/>
<button onclick="log()" id="submit" type="submit">add</button>
</form>
This is ajax php api:
function log() {
var OverTime_Description = $('#OverTime_Description').val();
var DateStart = $('#DateStart').val();
if (OverTime_Description != "" && DateStart != "") {
$.ajax({
url: 'https://severip/lineMsg.php?Group=101&Message=' + OverTime_Description + ":" + DateStart,
type: 'GET',
success: function (data) {
},
error: function () {
}
});
}
}
Passing two input text value which ID are OverTime_Description and DateStart.
My redirection in my OverTime crontroller:
public ActionResult Add()
{
try
{
ViewBag.Overtimess = OverTimeRepository.GetCollections().ToList();
ViewBag.Members = MemberRepository.GetCollections().ToList();
if (Request.Form.Count > 0)
{
OverTime _overTime = new OverTime();
_overTime.OverTime_Description = Request.Form["OverTime_Description"];
_overTime.OverTime_StartDate = DateTime.Parse(Request.Form["DateStart"]);
return RedirectToAction("Index");
}
return View(OverTimeRepository.GetCollections());
}
catch
{
return RedirectToAction("Index", "Error");
}
}

Autocomplete does not showing the results from controller in asp.net MVC

The autocomplete code written is getting the results from controller and is also showing when used F12 developer network tab with the browser. But the actual returned result is not showed by the textbox, only drop-down with no values are shown.
I'm including the codes of view and controller. Please help me out to solve this.
code of the view page :
<html>
<head><title></title>
<link href="~/Content/themes/base/jquery.ui.autocomplete.css" rel="stylesheet" />
<script type="text/javascript" >
$(document).ready(function () {
alert("hi");
$("#ValueField").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Customer/AutoretrieveCustomer",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
var items = $.map(data, function (item) {
return {
label: item.FirstName,
value: item.FirstName
};
});
response(items);
}
})
}
});
});
</script>
</head>
<body>
<div id="CusView">
<label for="FirstName">Enter Customer First name : </label>
Enter value : <input type="text" id="ValueField" />
</div>
</body>
</html>
code of the controller :
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult AutoretrieveCustomer(string term)
{
Banking.BankingDBEntities db = new BankingDBEntities();
var suggest = from s in db.Customers
select s.FirstName;
var namelist = suggest.Where(n => n.ToLower().StartsWith(term.ToLower()));
return Json(namelist, JsonRequestBehavior.AllowGet);
}
Also I would need the code for getting the id of the user selected item in the textbox.
The following the output pic when the autocomplete is executed
This bit in your controller action:
var suggest = from s in db.Customers
select s.FirstName;
var namelist = suggest.Where(n => n.ToLower().StartsWith(term.ToLower()));
Means that your controller action is actually returning an array of strings, not an array of objects like your success function is assuming.
You should be able to remove the mapping and just call response directly with the array of strings:
success: function (data) {
response(data);
}
Or, just:
success: response

Pass a value of textbox from view to controller through hyperlink in MVC ASP.NET

In View-
<input type="text" hidden="hidden" id= "nameString" name="nameString" value="xyz" />
#Html.ActionLink("Save", "HomePage", "ControllerName", new { nameString = "/* Value from above input here.*/" })
In this case I want to pass "xyz" through this hyperlink.
Can't use Get or POST methods to pass this value.
This HomePage view is not the current ActionLink view either, so can't grab the value in Controller using Request.Form["nameString"];
I tried JQuery like following but its not working-
var nameVar = document.getElementById('nameString').value;
$.ajax({
type: 'GET',
url: "#Url.Action("HomePage", "ControllerName")",
data: { nameString : nameVar }
});
I checked in debugger and saw that Controller is actually getting value and processing it but nothing is coming on browser. I am not sure how ajax works.
since the redirect will happen in jquery you don't need a helper
<input type="button" class="btnRedirect" value="Click Here" />
then in your script
$('.btnRedirect').on('click', function(){
var url = '#Url.Action("HomePage", "ControllerName", new { textValue = "----" })'.replace("----", $('#nameString').val());
window.location = url;
});
This is how it would be done with ajax although this will not handle returning a page.
var name = $("#nameString").value;
$.get("/ControllerName/HomePage",{ nameString : nameVar })
.done(function(){
window.location.assign("/ControllerName/HomePage");
});

Categories

Resources