This is my javascript, trying to go to an Url.Action using javascript.
function selectSchool() {
var url = '#Url.Action("SelectSchool", "Home", new { school = "_id_" })'.replace('_id_', $("#schoolSelect").val());
alert(url);
window.location.href = url;
}
The link in the alert looks fine, however the url goes back to the current view Home/Index?
What am i doing wrong?
HTML
<button class="btn btn-success" onclick="selectSchool()">Välj</button>
Related
I have a problem with passing the parameter via the link to the controller. The view in which I have a problem is to dynamically display the list of users, along with the possibility of searching for them. I did this part in js and it works fine. In this functionality in js I generate a link to the buttons, so that later, after pressing the button, you can save the selection in the database. Each link has an assigned user ID and user group ID. My problem is that when I press the button, nothing happens.
The following code represents the functionality described above. I would be very grateful for your help.
#if(ViewData[Enums.States.UserSelectWindow.ToString()].ToString() == "True")
{
<script type="text/javascript">
$("#UserlistCollectionId").css('height', $("#WindowUserSelectId").height() + 'px');
let users = #Html.Raw(Json.Serialize(UserModel.GetUsers()));
function Clear() {
$("#UserlistCollectionId").empty();
}
function FillAll(users) {
Clear();
for (user of users) {
$("#UserlistCollectionId").append('<li class="list-group-item"><div class="row justify-content-between"><div class="col-auto">' + user.name + '</div><div class="col-auto"><a class="btn btn-sm btn-success" asp-action="AddUserToGroup" asp-controller="Settings" asp-route-groupId=#Model.Group.Id asp-route-userId='+user.id+'>Wybierz</a></div></div></li>');
}
}
FillAll(users);
$("#SearchInputId").keyup(function () {
Clear();
let searchValue = $("#SearchInputId").val();
if (searchValue === "")
FillAll(users);
else {
for (user of users) {
if (user.name.includes(searchValue)) {
$("#UserlistCollectionId").append('<li class="list-group-item"><div class="row justify-content-between"><div class="col-auto">' + user.name + '</div><div class="col-auto"><a class="btn btn-sm btn-success" asp-route-groupId=#Model.Group.Id asp-route-userId='+user.id+'>Wybierz</a></div></div></li>');
}
}
}
});
</script>
}
In the above code, automatic link generation is performed using JQuery as follows:
$("#UserlistCollectionId").append('<li class="list-group-item"><div class="row justify-content-between"><div class="col-auto">' + user.name + '</div><div class="col-auto"><a class="btn btn-sm btn-success" asp-route-groupId=#Model.Group.Id asp-route-userId='+user.id+'>Wybierz</a></div></div></li>');
Unfortunately it doesn't work. In the inspection of the page you can see that the tag "a" does not have the attribute "href", only automatically puts all the code in quotes:
Screen of the html fragment in the browser
Firstly, you need read the doc about what does asp-route-{value} generate the url:
Any value occupying the {value} placeholder is interpreted as a potential route parameter. If a default route isn't found, this route prefix is appended to the generated href attribute as a request parameter and value
(/home/index?value=aaa). Otherwise, it's substituted in the route template. More explantion you could refer to the document.
Secondly, you do not specify the controller and action name, so the url will generate depending on your request url. That is to say, if the tag helper exists in Home/Privacy.cshtml, it will generate to:href="/home/privacy?value=aa".
Finally, Tag Helpers are interpreted. In other words, Razor must see them as actual tags in order to replace them. So what you did in js will not follow the tag helper generation principle, it's just a JS string. You need change the url like below:
<a class="btn btn-sm btn-success" href="/home/index?groupId=' +#Model.Group.Id+'&userId=' + user.id+'">Wybierz</a>
If the url matches the default route template, the url may like below:
<a class="btn btn-sm btn-success" href="/home/index/' +#Model.Group.Id+'/' + user.id+'">Wybierz</a>
Is there a way to call a Laravel route (with ID) inside a javascript?
Right now I'm getting encoded results and I'm stuck with this. I appreciate any help!. TY
I have this redirect link inside a javascript. This href is inside a datatable, once I click an icon it will redirect me to the page.
return `<a href = "{{ route('smshistory.view', ['id' => $smshistory->id]) }}" class="btn btn-link btn-success btn-just-icon btn-round" title="SMS History">
<i class="material-icons">sms</i>
<div class="ripple-container"></div>
</a>`;
My route:
Route::get('sms-history/{id}', 'SmsHistoryController#getView')->name('smshistory');
My controller:
public function getView($id) {
$smshistory = SmsOutboundsHistory::find($id);
return view('sms-history', compact('smshistory'));
}
I'm getting an encoded results for this:
http://127.0.0.1:8000/%7B%7B%20route('smshistory.view',%20['id'%20=%3E%20$smshistory-%3Eid])%20%7D%7D
I would like to have it like this. The URL + id
http://127.0.0.1:8000/sms-history/2
I would like to pass a list of ids to a view when i click on a link:
<a href="{% url 'app:manage_ids' %}?ids={{ids}}">
So i have created a template var and pass it to js:
{% with ids="" %}
<script type="text/javascript">
window.ids = "{{ ids }}";
</script>
{% endwith %}
I manage object ids when click on checkbox:
<input type="checkbox" class="checkbox" value="{{ object.id }}">
Adding or removing it to a list:
$('.checkbox').change(function() {
var id = $(this).val();
// if django template var is empty
var list_ids = [];
// else
var list_ids = window.ids;
if ($(this).is(':checked')) {
list_ids.push(id);
// here i have to save it on a django template var to use it on the click link
}
else {
const index = list_ids.indexOf(id);
if (index > -1) {
list_ids.splice(index, 1);
// here i have to save it on a django template var to use it on the click link
}
}
});
Anybody could help me about how to do it ?
Thanks you so much.
You cant update the django variable and expect it to update your href value of the link.
Moreover, you should not send the value of a GET query parameter as a list datastructure, instead you'll send it as ?ids=<value1>&ids=<value2>
To do this you'll have to first construct such string of url and then dynamically update the href of your hyperlink with it.
You can first decalre the string variable for you href in javascript somehwere as:
var id_link = "{% url 'app:manage_ids' %}?ids=";
Then whenever the click checkbox function is called you can add new value to this and update the href of link:
id_link += "&ids=" + id;
Add an id to your href and get it and update it
var a = document.getElementById('yourlinkId');
a.href = id_link
Now when someone clicks this link, you can get these in query parmeters in view as:
request.GET.getlist('ids')
and you shall get list of all IDs.
Note (My two cents): Ideally in a good archiecture this should happen by clicking a button with a post request from template in django.
I have this button which calls modal window with simple form.
<aui:button-row>
<a style="float: left" onclick="ITD.robomarket.activateKeyModalWindowFunction(
'${activateKeyURL}', '<%=LanguageUtil.get(pageContext, "key-activating")%>', '400', '334')" class="btn btn-green"> </a>
</aui:button-row>
I want to close this modal window after submitting. I have already done this:
function closeModal () {
var id = 'robomarket-activate-key-modal-window'
var dialog = Liferay.Util.Window.getById(id);
dialog.destroy();
}
And this function I call in .jsp:
<script>
$(document).ready(function() {
closeModal();
});
</script>
The problem is this doesn't work BUT that modal window closes when I write this lines in console! What's the problem?
You have to call closeModal from the JSP where the modal was opened.
For exemple A.jsp has a link that open B.jsp in a modal dialog, then you want to close B.jsp when form is submitted
Here is a possible implementation :
In A.jsp :
<portlet:renderURL var="popupUrl" windowState="<%=LiferayWindowState.POP_UP.toString()%>">
<portlet:param name="mvcPath" value="/B.jsp"/>
</portlet:renderURL>
<aui:button href="${popupUrl}" useDialog="true" value="Open in popup" />
and at the bottom of A.jsp :
<aui:script>
Liferay.provide(window, 'closePopup', function(dialogId) {
var A = AUI();
var dialogId = A.one('div.dialog-iframe-modal').get("id");
var dialog = Liferay.Util.Window.getById(dialogId);
dialog.destroy();
});
</aui:script>
Then in B.jsp
You have to say to the opener to close the dialog, here is a possible implementation :
<portlet:actionURL name="/submitForm" var="submitFormURL">
<portlet:param name="action" value="submitForm" />
</portlet:actionURL>
<aui:form action="<%= submitFormURL %>" method="post" name="fm" onSubmit='<%= "event.preventDefault(); " + renderResponse.getNamespace() + "submitForm();" %>'>
...the form
<aui:button name="submitForm" type="submit"/>
</aui:form>
And at the bottom of the B.jsp page :
<script>
function <portlet:namespace/>submitForm(){
AUI().use('aui-io-request', function(A) {
var url = '<%=submitFormURL.toString()%>';
A.io.request(
url,
{
method: 'POST',
form: {id: '<portlet:namespace/>fm'},
on: {
success: function() {
Liferay.Util.getOpener().closePopup('dialog');
}
}
}
);
});
}
</script>
Hope it helps
Regards
Arnaud
You are calling closeModal () method just after de DOM is ready. Wich mean you are asking to close even before the popUp is opened.
It is not clear what you do in your popUp. If is a partial submit, say an ajax call or similar, you need to call closeModal after you have got a response and treated the returned data.
Otherwise, if you are submiting a full submit, (a full reaload, navigation to a new page, you go through a whole new render phase) the modal window will dissapear with everi thing else in the currently renderes page.
I need to get request url (the Url of the Page/ActionMethod coming from)
As you can see guys when I click on any of my a href I'm calling ApplySelectedLanguage ActionResult from my Language controller.
I wanted to solve this by adding one hidden field which would be submitted and I could read the path easily,
something like this : "<%= Html.Hidden("requestUrl", Request.RawUrl) %>"
But I don't know where this can fit in this example so I could post it back
<ul class="dropdown-menu custom-dropdown-menu">
<li><%= Html.Hidden("requestUrl", Request.RawUrl) %>EN</li>
<li><%= Html.Hidden("requestUrl", Request.RawUrl) %>DE</li>
</ul>
I know it might be solved on server side using
HttpContext.Request.UrlReferrer,
but I would like to solve it with hidden field.
[HttpPost]
public ActionResult ApplySelectedLanguage(string requestUrl, int Lcid)
{
// requestUrl will contain the url of the page used to
// render the form
...
}
You should add Html.Hidden("requestUrl", Request.RawUrl) value in href attribute like this:
<script>
$(document).ready(function () {
$('.dropdown-menu.custom-dropdown-menu').find('a').attr("href", function () {
return this.href + $('#requestUrl').val();
});
});
</script>
But as #Stephen Muecke said better way is add requestUrl to #Url.Action like this:
href = "#Url.Action("ApplySelectedLanguage", "Language", new { Lcid = "1050", requestUrl = Request.RawUrl })"