In this code document.location returns as 'Content/Search/(the searchboxID's value)' . But when I try to make an another search in same page this time document.location return as Content/Search/(the searchboxID's first value)/(the searchboxID's new value) . How can I remove the first value everytime when I search and add $(searchboxID).val() as a route parameter in Url.Action ?
<input type="text" id="txtSearch" name="searchKey" size="21" maxlength="120" value="">
<input type="button" value=">" onclick='redirectOnClick()' id="srcButton">
<script type="text/javascript">
console.log("result:" document.getElementById('txtSearch').value)
$(document).ready(function () {
var test =document.getElementById('srcButton').addEventListener("click",redirectOnClick);
var searchboxID = "#txtSearch";
function redirectOnClick() {
var routeLink = document.getElementById('txtSearch').value;
console.log("route " routeLink)
document.location = '@Url.Action("Search","Content")' '/' $(searchboxID).val();
console.log(document.location.pathname);
$(searchboxID).empty();
//location.reload();
}
});
</script>
CodePudding user response:
But the url is
Content/Search/(the searchboxID's first value)/(the searchboxID's new value)
This is a common issue with using @Url.Action
where the framework will supply any missing parameters from your current model's properties.
Given a string parameter searchTerm
,
@Url.Action("Search", "Content")
becomes the same as
@Url.Action("Search", "Content", new { searchTerm = Model.SearchTerm })
So you need to explicitly provide that parameter with a blank value so that it is not rendered:
@Url.Action("Search", "Content", new { searchTerm = "" })
(or = string.Empty
)
Adding the original javascript component for the new value gives:
url = '@Url.Action("Search","Content", new { searchTerm = "" })' '/' $(searchboxID).val();