Mimicking a jquery hide from an MVC controller - c#

I have a numerical "badge" value that I'm trying to display on a menu in my MVC 5.1 app.
<span id="myBadge" class="badge menu-badge">#SessionData.MyCount</span>
I have a SessionData class so I don't have to pass around magic strings.
public class SessionData
{
const string MyCountKey = "MyCount";
public static int MyCount
{
get { return HttpContext.Current.Session[MyCountKey] != null ? (int)HttpContext.Current.Session[MyCountKey] : 0; }
set { HttpContext.Current.Session[MyCountKey] = value; }
}
}
The badge is initially populated from a base controller which performs a database call.
SessionData.MyCount = CountThingsFromDatabase();
I use javascript & jquery on the front-end as users modify data. If the count reaches 0, a jquery command hides the "0" badge.
function setBadgeValue(badgeName, count) {
$(badgeName).html(count);
count > 0 ? $(badgeName).show() : $(badgeName).hide();
}
All of this works fine with one exception. When the controller retrieves a count of "0", I'd like to hide the badge from the view in the same manner as the jquery show/hide commands. The front-end jquery piece works wonderfully, but I'm unsure of how to accomplish the same effect from the controller side of things.
Any help would be greatly appreciated.
Update 1:
The views I have utilize Telerik/Kendo objects. This is from a view which displays a Kendo grid. Each grid row has a button that is tied to this method. I'm not sure it would help to post the entire view/controller since most of it is Kendo related.
function addToCart(e) {
// Get the grid data
var grid = $("#Grid").data("kendoGrid");
var dataItem = grid.dataItem(grid.select());
// Add item to the cart
$.ajax({
url: 'Search/AddCart',
data: { itemId: dataItem.ItemId },
success: function () {
$('_MyBadge').html();
$('_Layout').html();
// Update the count
setBadgeValue("#myBadge", 1);
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert('Failed to add item #' + dataItem.itemId + ' to your cart.\nStatus: ' + textStatus + '\nError: ' + errorThrown);
}
});
}

How about doing this on the view?
#if (SessionData.MyCount == 0)
{
<span id="myBadge" class="badge menu-badge" style="display: none;">#SessionData.MyCount</span>
}
else
{
<span id="myBadge" class="badge menu-badge">#SessionData.MyCount</span>
}

No need to use the controller in any way, just hide your badge initially in the view if your count is zero.
<span id="myBadge" class="badge menu-badge" style="display: #(SessionData.MyCount > 0 ? "block" : "none");">#SessionData.MyCount</span>

Related

Jquery Autocomplete from Table

I am new and struggling to find a way to create a searchable dropdownlist (MVC5/C#). I have tried Select2, and could not get it working. I am desperate and out of time.
Looking at a few tutorials on Jquery Autocomplete, it seems pretty straight and forward. My problem is that all of the examples on line seems to use static data. My dropdownlist is populated from my Controller using a List of pre-filtered results.
This is how I populate my doprdownlist
List<SelectListItem> autocomplete = db.ICS_Supplies.Where(s => s.InvType == "F").Select(x => new SelectListItem { Value = x.Supplies_ID.ToString(), Text = x.Old_ItemID + " " + " | " + " " + " Description: " + x.ItemDescription, Selected = false }).DistinctBy(p => p.Text).OrderBy(p => p.Text).ToList();
ViewBag.FormsList = new SelectList(autocomplete, "Value", "Text");
As is, the dropdown populates - but it has a lot of records and is VERY slow.
From most of the examples I have seen online, the searchable items are something like:
var options = [
{ value: 'Adam', data: 'AD' },
// ...
{ value: 'Tim', data: 'TM' }
];
That's great, if I want to type out a thousand possible items - but I need to populate my DropDownList options from a table. .. and I am lost.
I am very new to Jquery and any direction is greatly appreciated.
EDIT1*
I am adding the View Code (from the online Example) for more clarification
<div class="form-group col-sm-5">
<label for="files">Select Supply:</label>
<input type="text" name="supplies" id="autocomplete" />
</div>
<div>
Selected Option : <span class="label label-default" id="selected_option"></span>
</div>
I suggest you need ajax to get a dynamic autocomplete list. Here's some sample code - it's the definition of a basic jQuery implementation that uses ajax.
function close_autocomplete($elemid) {
jQuery($elemid).autocomplete("destroy" );
}
function attach_autocomplete($elemid) {
jQuery($elemid)
.autocomplete({
delay : 250,
minLength : 3,
source : function( request, response ) {
var $thedata = request.term;
jQuery.ajax({
url : myajaxresponder.php,
type : "GET",
data : {
action_id : "autocomplete",
thedata : $thedata
},
error : function (jqXHR, textStatus, errorThrown){
console.log(textStatus + " " + errorThrown);
response("");
},
success : function (result) {
var resultarray = JSON.parse(result);
response(resultarray);
}
});
},
select : function ( event, ui ) {
jQuery($elemid).val(ui.item.value);
return false;
},
})
}
// attach the handlers
jQuery("#myid").focus(function ()
{attach_autocomplete(jQuery(this).prop("id"))});
jQuery("#myid").blur(function ()
{close_autocomplete(jQuery(this).prop("id"))});

MVC Controller Different Behavior between Form Submit and Ajax call

I am pretty new to MVC and web development in general so please bear with me.
In my web app, I am trying to call a controller action via an Ajax request as I only want to refresh the partial view in my page as opposed to the entire page. Everything works properly (the Partial View is returned without refreshing the main View) except the Partial View returns the wrong values. After some debugging I discovered the error was with the Request statements in the controller action. When the controller action is called by a normal form submit, the Requests are able to get the user input values, but not when I call the controller with an Ajax request; they simply return null values.
Please see the below example, it is a much much simplified version of what I am facing. When using Ajax, the total always ends up being 0 due to the parse commands failing on a null value.
Controller:
[HttpPost]
public ActionResult Calculate() {
ViewBag.Total = 0;
for(int i = 1; i < 10; i++) { // max number of Frames that users can add is 10
string FrameNumber = i.ToString;
try {
string rawValue1 = Request["input1_Frame" + FrameNumber];
string rawValue2 = Request["input2_Frame" + FrameNumber];
decimal Value1 = decimal.Parse(rawValue1);
decimal Value2 = decimal.Parse(rawValue2);
ViewBag.Total += Value1 + Value2;
} catch {
break;
}
return PartialView("Banner");
}
JQuery:
$("#calculate").on("click", function () {
$.ajax({
cache: false,
dataType: 'text',
type: "POST",
url: "/Home/Calculate",
success: function (data) {
$(".banner").html(data);
},
error: function () {
alert("Something went wrong in the controller");
}
});
return false;
})
View:
<div class="banner"></div>
<input name="input1" type="text">
<input name="input2" type="text">
<button id="calculate">Calculate Total</button>
Partial View:
<div>
Total:
<span id="totalValue">#ViewBag.Total</span>
</div>
EDIT: So just to clarify as to why I don't just pass the values as Ajax parameters is because in my actual view, the number of inputs is dynamically generated with JQuery. For example, I have a frame with 15 inputs, but users may choose to add additional frames - so in total there will be 30, 45, 60,... or more inputs. I'm not exactly sure how to handle Ajax parameters that way, so for each frame I loop 15 times, increment the input ID each time, and request the data that way. I've updated the code for the controller to better visualize what I'm saying.

Get Dynamically Created TextBox ID From Razor To jQuery

I am trying to get the dynamically created TextBox ID into jQuery from Razor view. The IDs are created in HTML as follows:
Product - 1: cartDetails_0__Quantity
Product - 2: cartDetails_1__Quantity
Right now, when I give the above inputs directly to Ajax call, it updates the corresponding rows. As an example:
#if (ViewBag.Cart != null)
{
for (int i = 0; i < cartDetails.Count(); i++)
{
<tr>
<td style="text-align: center;">#Html.TextBoxFor(model => cartDetails[i].Id)</td>
<td style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].IP)</td>
<td style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].ProductName)</td>
<td style="text-align: center;">#Html.DisplayFor(model => cartDetails[i].Price)</td>
<td style="text-align: center;">#Html.TextBoxFor(model => cartDetails[i].Quantity, new { #class = "quantityUpdate", data_id = cartDetails[i].Id })</td>
</tr>
}
}
var url = '#Url.Action("UpdateCart2")';
$(".quantityUpdate").change(function () {
var id = $(this).data('id');
$('.quantityUpdate').each(function (i, item) {
$.post(url, { id: id, quantity: $('#cartDetails_' + 0 + '__Quantity').val() }, function (response) { //cartDetails_0__Quantity - The first TextBox ID
if (response) {
$("#TotalPrice").load(window.location + " #TotalPrice");
}
});
})
alert($('#cartDetails_' + 0 + '__Quantity').val());
});
Is there any way to loop through jQuery to get the dynamically generated TextBox ID in Razor? I've tried the following but doesn't get the value:
$('.quantityUpdate').each(function (i, item) {
$.post(url, { id: id, quantity: $('#cartDetails_' + i + '__Quantity').val() }, function (response) { //cartDetails_0__Quantity - The first TextBox ID
if (response) {
$("#TotalPrice").load(window.location + " #TotalPrice");
}
});
})
Even tried this one but it gets the value of first TextBox only:
$('.quantityUpdate').each(function (i, item) {
$.post(url, { id: id, quantity: $(this).val() }, function (response) { //cartDetails_0__Quantity - The first TextBox ID
if (response) {
$("#TotalPrice").load(window.location + " #TotalPrice");
}
});
})
Note: I am trying to update rows giving input to the TextBoxes with Ajax call. The TextBoxes are in a loop in the view. In this regards, I've to get the IDs of the dynamically generated HTML IDs.
You can use create event of dynamically created elements in order to get their Ids.
But bear in mind to use this you need to use On(). See http://api.jquery.com/on/
See also:
Event binding on dynamically created elements?
In jQuery, how to attach events to dynamic html elements?
PS. If there is a cleaner way to get dynamically created elements I would also be glad to get it :)
Edit. Maybe I was not clear enough . There is no exactly "create" event. You just can hook any actions you need to On()
See also jQuery "on create" event for dynamically-created elements

C# MVC No submit pass object between views

I am sorry for my typos.I am working on proof of concept C# ASP.NET MVC application where I need to pass data between two views when there is no post and get. One view launches a modal dialog and I need communication between them. We are using JQuery.
I have a view called Charges.cshtml with a data grid. The first column of the datagrid may have span element or a link element depending on a
property which will tell whether the charge have single or multiple descriptions. The view looks like below.
If the charge has multiple descriptions user will click the corresponding description link( Description2 in this case ) and a modal dialog will open showing various descriptions like below
Now in this modal dialog user will confirm/select one description. Now I need to close the modal dialog and update the description of selected
charge like below
The hard part here is how to pass data between two views. I am ok to pass data via controller or via javascript.
I tried various ways to pass selected charge from Charges.cshtml to LoadLoanChargeDescriptions method in LoanCharge controller like json serialize, ViewData, ViewBag, TempData and so on but of no use. I can pass simple data types like int, string, float but not whole object. I feel I need to pass CurrentDescription and Descriptions to my controller and from their I need to move to other pieces. I tried to pass List of strings but could not see how to access them in controller since I got count as 0 in my controller. I am able to open popup of multiple descriptions UI ( for now just added Hello text )
Please see below for my code snippets
Charges.cshtml
#model ChargeViewModel
#using (Html.FAFBeginForm())
{
<div>
<table>
<tbody>
<tr >
//.....
<td>
#if(Model.IsMultipleMatch)
{
var loanCharge = Model as ChargeViewModel;
if (loanCharge.IsMultipleMatch == true)
{
//string vm = #Newtonsoft.Json.JsonConvert.SerializeObject(loanCharge);
<span>
<a
onclick="ShowMatchingDescriptions('#Url.Action("LoadLoanChargeDescriptions", "LoanCharge")','', '920','500')">
#loanCharge.Description
</a>
</span>
}
}
else
{
<span>Model.Description</span>
}
</td>
</tr>
</tbody>
</table>
</div>
}
public class ChargeViewModel
{
public string Description {get;set;}
public bool IsMultipleMatch {get;set;}
public List<string> Descriptions {get;set;}
}
public class LoanChargeController
{
public ActionResult LoadLoanChargeDescriptions()
{
// get data here and pass/work on
return View("_PartialMultipleMatchPopup", null);
}
}
In Review.js
function ShowMatchingDescriptions(popUpURL, windowProperties, w, h) {
try {
var left = (screen.width / 2) - (w / 2);
var top = (screen.height / 2) - (h / 2);
var properties = windowProperties + "dialogwidth:" + w + "px;dialogheight:" + h + "px;dialogtop:" + top + "px;dialogleft:" + left + "px;scroll:yes;resizable:no;center:yes;title:Matching Lender’s Fee;";
$.when(
window.showModalDialog(popUpURL, window, properties)
)
.then(function (result) {
var childWindow = result;
});
}
catch (err) {
alert("Error : " + err)
}
}
UPDATE 1
I updated my question and posted more details.
Thanks in advance.
UPDATE 2
Please see for my solution at below link.
MVC pass model between Parent and Child Window
Why don't you use the AJAX for pass the data?
function ChargeViewModel() {
this.Description ='';
this.IsMultipleMatch =false;
}
var chargeViewModel= new ChargeViewModel();
var data = JSON.stringify({ 'chargeViewModel': chargeViewModel });
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'html',
type: 'POST',
url: '#Url.Action("LoadLoanChargeDescriptions", "LoanChargeController")',
data: data,
success: function (result) {
//result will be your partial page html output
},
failure: function (response) {
}
});
Then you have to change the controller like this:
public ActionResult LoadLoanChargeDescriptions(ChargeViewModel chargeViewModel)
{
// get data here and pass/work on
return View("_PartialMultipleMatchPopup", null);
}
Let me know you have queries..

Saving values of html selects and re-select them on postback

I have five dropdownlists in form of html selects. The first binds at page load using jQuery, and the rest bind when the previous dropdown has been selected. I also have five hidden fields for each dropdown which stores the selected values.
My problem is that when I do a post back, i.e. click the "Search" button, I have to re-populate the dropdowns and select the correct values again by using the ID's in the hidden fields. So far, I've come up with no good way to do this.
In the .aspx page:
<select name="boxFunktionsnedsattning" id="boxFunktionsnedsattning" multiple="multiple </select>
<asp:TextBox ID="HiddenBoxFunktionsnedsattning" runat="server" />
<script type="text/javascript">
function boxFunktionsnedsattningPopulate() {
$.ajax({
type: "POST",
url: "Sok.aspx/getFunktionsnedsattningar",
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: LoadBoxFunktionsnedsattning,
failure: function (response) {
alert(response);
}
});
}
//============================================================================================================
function LoadBoxFunktionsnedsattning(response) {
var result = response.d;
var options = $("#boxFunktionsnedsattning");
options.text(''); // clear the box content before reloading
if ($('#boxFunktionsnedsattning').val != '') {
options.removeAttr("disabled");
options.multipleSelect("enable");
}
else {
options.attr("disabled", true);
options.multipleSelect("disable");
}
$.each(result, function () {
options.append($("<option />").val(this.id).text(this.name));
});
UpdateBoxEnabledState();
options.multipleSelect("refresh");
}
</script>
Backend code:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Funktionsnedsattning[] getFunktionsnedsattningar()
{
GetDataService.IgetDataClient gdc = new IgetDataClient();
return gdc.getFunktionsnedsattningAll();
}
I should add that I'm a beginner when it comes to jQuery, so there is probably something I've overlooked.
IF your using webforms use an onclick function to post back to the server instead of a submit. I think this is the functionality you want because the variables in the inputs of the form will keep its value. Is the search button returning results on the same page or a different one because it will determine the ease in which you can keep varibles during a post back. Good luck!
Got it working with the following solution:
function fillFunktionsnedsattning() {
//stores the value of selected items
var $fn = $('#<%=HiddenBoxFunktionsnedsattning.ClientID%>');
//creates an array of the values in the hidden field
var fnSplit = $fn.val().split(",");
//val() accepts an array which it uses to select items in the list (go figure)
$("#boxFunktionsnedsattning").val(fnSplit);
$("#boxFunktionsnedsattning").multipleSelect("refresh");
//function that triggers the binding of the next dropdown
boxFunktionsnedsattningOnChange();
}
For it to work, this function needs to be called in the function that populates the dropdown. Each dropdown needs it's own fillFunction to be called in the same place, like this, for an example:
function LoadBoxFunktionsnedsattning(response) {
var result = response.d;
var options = $("#boxFunktionsnedsattning");
options.text(''); // clear the box content before reloading
if ($('#boxFunktionsnedsattning').val != '') {
options.removeAttr("disabled");
options.multipleSelect("enable");
}
else {
options.attr("disabled", true);
options.multipleSelect("disable");
}
$.each(result, function () {
options.append($("<option />").val(this.id).text(this.name));
});
fillFunktionsnedsattning();
UpdateBoxEnabledState();
options.multipleSelect("refresh");
It's probably possible to simplify this, but this works for me.

Categories

Resources