Calling Javascript functions from href defined in Razor file - c#

So I have this function cart.remove(itemid), that removes an item from the shopping cart using an ajax call. The cart object is defined in its own javascript file and its functions are accessible and the remove() function works properly to remove items as intended. Upon clicking the link below, an alert pops up, confirming if you really want to remove the item. If yes, it removes the item from the shopping cart.
#if (Model.Count > 0)
{
foreach (var item in Model.Items)
{
<div><a title="Remove item from cart" href="javascript:cart.remove(#(item.ItemID));">Remove Item</a></div>
}
}
Now, due to complexity of the different types of items in the shopping cart, for a more user friendly UI, I need the confirm-remove-item alert text to be different, depending on the item that is clicked. I have a function defined in the model, GetRemoveItemAlertText(int itemid) that returns the appropriate text. I wrap that text in a json object so that the text isn't visible as one of the remove() function's parameters, when someone hovers over the link, in the browser statusbar.
The javascript remove() function has been redefined to remove(itemid, alerttext) to display the custom remove text, instead of the same text every time. No other changes to that function; it still displays an alert and removes the item if the user clicks yes to the confirmation. Here is my attempt at removing the item with the custom alert text:
#if (Model.Count > 0)
{
foreach (var item in Model.Items)
{
var alert = Model.GetRemoveItemAlertText(item.ItemID);
<script type="text/javascript">
function removeItem_#(item.ItemID)() {
var bodytext = "#UriEscapeDataString(alertText)";
var alerttext = {
bodytext: bodytext
};
cart.remove(#(item.ItemID), alerttext);
}
</script>
<div><a title="Remove item from cart" href="javascript:cart.removeItem_#(item.ItemID)();">Remove Item</a></div>
}
}
Since the javascript function is defined inside a loop, the name needs to be different each time, hence the itemid in the function name. It should grab the custom remove-item text and then call cart.remove(), just like it was previously being done inside the href definition. The problem is that this function removeItem_#(item.ItemId)() is not being called. Even if I just put an alert() or console.log() inside the function, the code never fires. Is there anyway to accomplish this? I've also tried calling that function by using a click listener bound to a class that is on a <span>' or`. Any suggestions? I can clearly see, by viewing the page source, that each of the cart's current items have their own remove-item function defined, but for some reason, the code isn't reachable.

Try this on for size, of course all of this can be done MUCH easier with JQuery if you would like a much better solution:
#if (Model.Count > 0)
{
foreach (var item in Model.Items)
{
<div><a title="Remove item from cart" id="#item.ItemID" hreaf="javascript:return RemoveItem(#item.ItemID);" data-message="#Model.GetRemoveItemAlertText(item.ItemID)">Remove Item</a></div>
}
}
<script>
function RemoveItem(itemId)
{
var element = document.getElementById(itemId.toString());
var alerttext = element.getAttribute('data-message');
return cart.remove(#(item.ItemID), alerttext);
}
</script>
Much better if we can use JQuery:
#if (Model.Count > 0)
{
foreach (var item in Model.Items)
{
<div><a title="Remove item from cart" href="#" class="cart-item" data-itemid="#item.ItemID" data-message="#Model.GetRemoveItemAlertText(item.ItemID)">Remove Item</a></div>
}
}
<script>
$(document).ready(function(){
$('.cart-item').click(function(e){
e.stopProgagation();
cart.remove($(this).data('itemid'), $(this).data('message'));
});
});
</script>

Related

How to pass an ID parameter to Blazorise modal on button click, from one component to another?

I'm new and trying to formulate this as best as I can. There's so much new concepts to get a hold of! Please tell me if I'm unclear.
I'm making a Todo-app as an exercise. On page load I get todo items from the database and iterate them in a foreach-loop, each todo is assigned an X-button for removal. This was easy, but for modifying a todo text I want an update button that brings up Blazorise's modal popup, to use it's input field.
My problem is that I don't get how to pass each todo item's id into this modal, for each button that is. For the remove button I could use the foreach loop's "todoItem.Id" variable, but as the Blazorise modal is another component I can't.
Here's how my Index page looks:
#page "/"
#using TodoApp.App.Components
<section class="todo-container">
#if (TodoItems != null)
{
#foreach (var todoItem in TodoItems)
{
if (todoItem.IsDone == false)
{
<div class="todo-item">
<p>#todoItem.Text</p>
<UpdatePopup OnTodoItemUpdated="UpdateAndLoad"></UpdatePopup>
<Button class="remove-btn" Clicked="(() => RemoveTodoItem(todoItem.Id))">X</Button>
</div>
}
}
}
</section>
<Popup OnTodoItemAdded="UpdateAndLoad"></Popup>
This button is inside the modal itself: <Button Clicked="#ShowModal">...</Button>, and I would've wanted to do the same thing as with the remove button, adding something like () => UpdateTodoItem(todoItem.Id).
How to get the ID from each item in the Index component and add this to each button in the Modal component?
There are multiple problems with your solution. First, you're creating a modal for each todo item (UpdatePopup) which is very inefficient. You should instead create just one update modal and use it for all the items.
#page "/"
#using TodoApp.App.Components
<section class="todo-container">
#if (TodoItems != null)
{
#foreach (var todoItem in TodoItems)
{
if (todoItem.IsDone == false)
{
<div class="todo-item">
<p>#todoItem.Text</p>
<Button class="update-btn" Clicked="(() => updatePopupRef.Show(todoItem))">Edit</Button>
<Button class="remove-btn" Clicked="(() => RemoveTodoItem(todoItem.Id))">X</Button>
</div>
}
}
}
</section>
<UpdatePopup #ref="#updatePopupRef" OnTodoItemUpdated="UpdateAndLoad" />
<Popup OnTodoItemAdded="UpdateAndLoad" />
#code{
UpdatePopup updatePopupRef;
}
And then in UpdatePopup you have something like this:
void Show(TodoItem item)
{
this.Item = item; // use this to bind item values to input fields
modalRef.Show(); // you also need to have modalRef set with #ref attribute
}
and in razor
<TextEdit #bind-Text="#Item.Name" />
PS. I haven't tested this code but you should have an overall idea :)

Increment Value on Model using Ajax and Razor

I'm looping through a collection on my model using Razor to display it. As an example:
#foreach(var item in myCollection)
{
<span id='item-#item.Id'>#item.Quantity</span>
<button type='button' onclick='updateQuantity(#item.Quantity+1);'>Add One</button>
}
In this example, updateQuantity performs an AJAX request, gets the new quantity back, and updates item-#item.Id with the new quantity. However, because #item.Quantity is pulled from the model (passed in via the page's GET method, #item.Quantity is never updated with the new value until the page is reloaded.
My question is: How can I make sure I'm always using the latest value, without having to reload the page?
Change the button inside your foreach loop like this:
#foreach(var item in myCollection)
{
<span id='item-#item.Id'>#item.Quantity</span>
<button id='updateButton' type='button'>Add One</button>
}
And, add this script to your View:
<script>
$("#updateButton").click(function() {
var quantity = $("#item-#item.Id").text();
updateQuantity(quantity);
})
</script>
And, in your updateQuantity() function, update the text inside the span after getting it back through Ajax.

How to filter data from dynamically generated list?

Currently I am working on one web application in asp.net.
Application received data from web-service in json format. Requirement is to develop controls dynamically, I did it using html controls. I dynamically created list of label & stored values in it. Now I want to add filter on the top of that list so that it can filter data based on vales entered in the textbox.
I want something like below textbox list of data like item1, item2 and so on, based on value entered in textbox. I need to filter data.
How I can achieve this?I tried to use list.js but it didn't work.
<% foreach (var item in (List<string>)Session["list"])
{
%>
<%--<li><label onclick="redirect('<%:item %>')"><%: item %></label><br/></li>--%>
<li><%:item %></li>
<% } %>
Add texbox with onkeyup event handler, set some id to ul e.g. id="list"
<input type="text" onkeyup="filter(this)" />
<ul id="list">
<li>a</li>
<li>abc</li>
<li>bcd</li>
<li>abc</li>
</ul>
Add the following script (source) and a reference to jquery
<script>
function filter(element) {
var value = $(element).val();
$("#list > li").each(function() {
if ($(this).text().search(value) > -1) {
$(this).show();
}
else {
$(this).hide();
}
});
}
</script>
Demo: http://jsbin.com/hahodetu/1/edit?html,output

Generate jQuery functions dynamically mvc 4 razor

Currently, I am passing a list of object from controller to a view, and generate labels by the object's name.
What I am trying to do is to generate a jQuery function that will Dynamically create functions (toggle a form with relative lable id) for each label after being clicked.
The jQuery function is not working, I could not output the corrent jQuery function in the webpage...... Could you give me soem hints?
<table>
#foreach (var item in Model)
{
<tr>
<td>
#Html.Label(item.productName, new { #id = item.productId})
</td>
</tr>
}
</table>
<script type="text/javascript">
$(document).ready(function () {
#foreach (var item in Model)
{
$(#item.productId).click)(function({
//do something
}));
}
});
</script>
Thanks very much!
your JS syntax is wrong, for starters. What you want to do is to give all those labels a class name (such as product_lbl) or a data attribute (if you don't like semantic class names) such as product-lbl. This way you don't have to do a second loop to add click event handlers. You'll only need one, like so:
$('.product_lbl').on(
'click',
function() { /* Do something for whichever label was clicked */ }
);
OR
$('[product-lbl]').on(
'click',
function() { /* Do something for whichever label was clicked */ }
);

Update div tag without refresh the whole page using JavaScript

I am developing a customizable drop down lists using HTML and JQuery, this drop down lists are containing a hidden html div tag and input text element. If the user click on the input element the jquery code shows the hidden div tag and allow him to choose one of the list items which are embedded inside the hidden div tag. After the user chose his desire item a JavaScript code runs and reflect his chosen item to the text element. here is the html code:
<input type="text" readonly="true" class="reg-content-datacell-textfield" style="cursor:pointer;width:270px;float:left;display:inline-block" id="txtSector" name="txtSector" />
<br />
<div id="ddlSector" style="left:26px;" class="ddlist">
<ul>
<%
MainDatabaseOperationsClass.DatabaseOperations databaseOperations = new MainDatabaseOperationsClass.DatabaseOperations();//db connection class
string sqlStatement = "select * from Dbtsniper02.dbo.Sectors";//get all database sectors
System.Data.SqlClient.SqlDataReader sqlDataReader = databaseOperations.getDataFromDBAsSQLDataReader(sqlStatement);//execute sql statement
while (sqlDataReader.Read())
{
%>
<li class="ddlListSector"><% Response.Write("(" + sqlDataReader[0].ToString() + ") " + sqlDataReader[1].ToString()); %></li>
<%
}
%>
</ul>
JavaScript Code:
$(document).click(function (event) {
if ($(event.target).parents().index($('#ddlSector')) == -1) {
if ($('#ddlSector').is(":visible")) {
$('#ddlSector').slideToggle();
}};
$(document).ready(function () {
$("#txtSector).click(function (e) {
$("#ddlSector").slideToggle();
e.stopPropagation();
return false;
});
$("#ddlSector").click(function (e) {
//disallow hide the current drop down list when you click on it direcly
e.stopPropagation();
return false;
});
$(".ddlListSector").click(function (e) {
//relect you selection of the drop down list to the parent input text field
if ($('#ddlSector').is(":visible")) {
document.getElementById('txtSector').value = '';
document.getElementById('txtSector').value = $(this).html();
$('#ddlSector').slideToggle();
}
});});
Now, my question is if I've others drop down lists like the above one, how I can Update their items data according to the user choice from the above drop down list. I'm gonna do that via change the sql statement according to the value of the text element associated with the desired drop down list but I do not know how I can trigger the event for update only the div tag content if the user select one of the drop down list items
Thank you very much, I'm highly appreciate your cooperation
It sounds like you want to use an AJAX call inside the ddlListSector click event listener. Make a server file that will expect the value selected and return the list of values you want (probably using a sql command). The AJAX could return plain text, JSON, or even full markup depending on how involved you want the front end to be. In the success callback of the AJAX call, update the contents of whatever other drops you have. It looks like your already using jQuery, so I recommend their docs.

Categories