How can I compare a value from C# Viewbag in Javascript? - c#

I want to compare a boolean value from the Viewbag in javascript. So at first I tried this:
if (#Viewbag.MyBoolValue)
do_sth();
But then I have error in console like: Value False/True is not declared (not exactly).
So I tried this:
#{
string myBool = ((bool)Viewbag.MyBoolValue) ? "true" : "false";
}
and in javascript:
if (#myBool == "true")
do_sth();
But it does not work too. How can I make it work? Any help would be appreciated.

What you have should work, assuming that the value from the ViewBag is of a type which javascript can understand.
Note however, that your first example most likely did not work because boolean values are lowercase in javascript and uppercase in C#. With that in mind, try this:
var myBoolValue = #ViewBag.MyBoolValue.ToString().ToLower();
if (myBoolValue)
do_sth();

The below will create a javascript vailable with value from viewbag
<script>
var myBoolInJs = #Viewbag.MyBoolValue;
if(myBoolInJs == true)
do_sth();
</script>

var myBoolVal = #((ViewBag.MyBoolValue ?? false).ToString().ToLower());
or
var myBoolVal = '#(ViewBag.MyBoolValue)'==='#true';
or
var myBoolVal = #(Json.Encode(ViewBag.MyBoolValue ?? false));

This will work.
#{
string myBool = Viewbag.MyBoolValue.ToString().ToLower();
}
if (#myBool)
do_sth();

Insted true and false use 0 and 1 in your controller, on top of razor page
#{
var isSomething= Viewbag.MyBoolValue;
}
Later down
if (#isSomething== 0)

Related

setting the value of textbox equal to address bar in MVC4?

How can I set the Textbox's value equal to address bar?
for example :
localhost:28362/?f=Ava
when we click on a button the value of textbox must set to : Ava
?
Try this, Add Query String Jquery Js(querystring-0.9.0-min.js) in solution
$("#ButtonId").click(function(){
$("#textBoxID").val($.QueryString("f");)
});
Here is Javascript function to get query string value:
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Then you need to assign this value to a textbox. I would use jQuery:
$(function(){
$("#myTextBoxID").val(getParam("f"));
})
If you want a solution that uses MVC4 rather than JavaScript, define your controller method as:
public ActionResult Index(string f) {
return View(f);
}
In your view, you would then use one of:
#model string;
#Html.TextBoxFor(Model)
or
#model string
<input type='text' value='#Model' name='myValue' />
Obviously this is vastly oversimplified, but should give you a good starting point.

Is it possible to get data from C#/Razor in jQuery by way of HTML?

I want to get data from a C# function, store it in a hidden HTML field, and then access it in jQuery.
This is what I'm thinking:
C#:
public static string getDuckbillDepts()
{
List<string> duckbillDptsStr = new List<string>();
for (int i = 2; i < 100; i++)
{
duckbillDptsStr.Add(i);
}
return string.Join(",", duckbillDptsStr); // <-- will this work?
}
Razor:
// I first wanted to use List<int> but then realized HTML would probably mutiny if I tried to give it that data type
#{string duckbillDeptsCSV = CCRReporterUtils.getDuckbillDepts()}
HTML:
<input type="hidden" name="AllDepts" id="hiddenAllDepts" value="#duckbillDeptsCSV" />
jQuery:
var deptsArray = $('hiddenAllDepts').val();
...but "duckbillDeptsCSV" in the HTML is red, indicating (right?) that it's confusing the compiler. Am I doing it wrong?
You could replace your <input type="hidden"... with Html.Hidden:
#Html.Hidden("AllDepts", duckbillDeptsCSV, new { id = "hiddenAllDepts" })
And update your jQuery to use # to tell it to look for that id (as is, it's looking for a <hiddenAllDepts> tag)
var deptsArray = $('#hiddenAllDepts').val();
If you are not against having some JavaScript within the MVC View, then you can just add the code directly into the JavaScript. e.g.
<script>
var deptsArray = '#CCRReporterUtils.getDuckbillDepts()';
</script>
This is just an alternative way to the other answers.
To convert this into an array you should be able to just do something like;
var deptsArray = ('#CCRReporterUtils.getDuckbillDepts()').split(',');
You can just instantiate a variable in javascript passing it the C# value and then retrieve it in jquery. Using Html.Raw and the Json.Encode method
In C# return the array instead of joining it:
public static List<string> getDuckbillDepts()
{
List<string> duckbillDptsStr = new List<string>();
for (int i = 2; i < 100; i++)
{
duckbillDptsStr.Add(i.ToString());
}
return duckbillDptsStr;
}
In your view you would have something like:
<script type="text/javascript">
var deptsArray = #Html.Raw(Json.Encode(CCRReporterUtils.getDuckbillDepts()));
</script>
And then in jquery you would just do something with it, since you would have an array of strings it seems:
<script type="text/javascript">
$.each(deptsArray, function (i,e) {
// Do something with each value
});
</script>
Try using the right # filter with jquery to get the element by id, for sample:
var deptsArray = $('#hiddenAllDepts').val(); // get a string
If you want a array, you have to use .split() method of javascript and get the value as a array, for sample:
var deptsArray = $('#hiddenAllDepts').val().split(','); //get a array of strings

ASP.Net MVC EditorTemplate wrong Id

So I have a double field called Area. I print it this way:
<div>#Html.EditorFor(model => model.Area)</div>
My EditorTemplate for Double looks like this:
#{
var attributes = this.ViewData.ModelMetadata.ContainerType.GetProperty(this.ViewData.ModelMetadata.PropertyName).GetCustomAttributes(true);
var htmlAttributes = GAtec.AgroWeb.Basic.Ux.Web.Helpers.EditorTemplateHelper.GetAllAttributes(ViewData, attributes);
var decimalPlaces = htmlAttributes["data-format"].ToString().Split(',');
var value = decimalPlaces.Length > 1 ? Model.ToString("n" + decimalPlaces[1]) : Model.ToString();
#System.Web.Mvc.Html.InputExtensions.TextBox(this.Html, Html.NameFor(model => model).ToString(), value, htmlAttributes);
}
<script>
$(document).ready(function () {
$("##Html.IdFor(model => model)").restrictNumber();
});
</script>
Nice, but why the html element comes wrong as <input id="Area_Area" /> and the jQuery selector comes right as $("#Area") ?
Both NameFor and IdFor returns "Area" when I watch them on debbuging.
UPDATE:
My htmlAttributes(As #DarinDimitrov asked) returns this array:
["data-min": "0.0", "data-format": "0,2"]
What's the point of stuffing gazilions of inline scripts inside your view (one for each editor template), when you could simply append a class="number" to your input field and then externalize your javascript in a separate file (which is where javascript belongs) and simply use a class selector:
$(document).ready(function () {
$(".number").restrictNumber();
});
#System.Web.Mvc.Html.InputExtensions.TextBox(this.Html, "", value, htmlAttributes);
This resolved my problem. The point is, the MVC knows the model name so you don't have to say him what to print. If you do, it will concat with the model name. But why it does this, I really don't know.

jQuery text() with <select>

I have a drop downlist as follows:
<select id="example" name="example" runat="server">
which gets populated in the code behind like this:
example.DataSource = new CampControl().GetCountries();
example.DataTextField = "CountryDesc";
example.DataValueField = "ID";
example.DataBind();
example.Attributes.Add("multiple", "multiple");
and on the click of the items in the list I have a jQuery function:
$inputs = this.inputs,
$checked = $inputs.filter(':checked'),
$checked.each(function (index) {
alert($(this).text());
});
But $(this).text() is always coming back as an empty string,
Am I doing anything wrong? Please help
Thanks in advance.
You are looking for the :selected attribute, not :checked
try this:
$inputs = this.inputs,
$checked = $inputs.filter.is(':checked'),
$checked.each(function (index) {
alert($(this).text());
});
try this one
$inputs = this.inputs;
$checked = $inputs.val();
$checked.each(function (index) {
alert($(this).text());
});
I got the value using this:
$inputs = this.inputs,
$checked = $inputs.filter(':checked'),
$checked.each(function () {
alert(($(this)[$(this).index()].title));
In drop downlist we need to populate n'of option to select ,after selecting the option. we can get selected text using below query...
var exampleValue = $("#example option:selected").text();

Best way to check if a drop down list contains a value?

When the user navigates to a new page, this ddl's selected index is determined by a cookie, but if the ddl doesn't contain that cookie's value, then I'd like it to be set the 0. What method would I use for the ddl? Is a loop the best way, or is there a simply if statement I can perform?
This is what I've attempted, but it doesn't return a bool.
if ( !ddlCustomerNumber.Items.FindByText( GetCustomerNumberCookie().ToString() ) )
ddlCustomerNumber.SelectedIndex = 0;
There are two methods that come to mind:
You could use Contains like so:
if (ddlCustomerNumber.Items.Contains(new
ListItem(GetCustomerNumberCookie().ToString())))
{
// ... code here
}
or modifying your current strategy:
if (ddlCustomerNumber.Items.FindByText(
GetCustomerNumberCookie().ToString()) != null)
{
// ... code here
}
EDIT: There's also a DropDownList.Items.FindByValue that works the same way as FindByText, except it searches based on values instead.
That will return an item. Simply change to:
if (ddlCustomerNumber.Items.FindByText( GetCustomerNumberCookie().ToString()) != null)
ddlCustomerNumber.SelectedIndex = 0;
If 0 is your default value, you can just use a simple assignment:
ddlCustomerNumber.SelectedValue = GetCustomerNumberCookie().ToString();
This automatically selects the proper list item, if the DDL contains the value of the cookie. If it doesn't contain it, this call won't change the selection, so it stays at the default selection. If the latter one is the same as value 0, then it's the perfect solution for you.
I use this mechanism quite a lot and find it very handy.
What about this:
ListItem match = ddlCustomerNumber.Items.FindByText(
GetCustomerNumberCookie().ToString());
if (match == null)
ddlCustomerNumber.SelectedIndex = 0;
//else
// match.Selected = true; // you'll probably select that cookie value
On C# this works:
if (DDLAlmacen.Items.Count > 0)
{
if (DDLAlmacen.Items.FindByValue("AlmacenDefectoAndes").Value == "AlmacenDefectoAndes")
{
DDLAlmacen.SelectedValue = "AlmacenDefectoAndes";
}
}
Update:
Translating the code above to Visual Basic doesn't work. It throws "System.NullReferenceException: Object reference not set to an instance of an object.."
So. for this to work on Visual Basic, I had to change the code like this:
If DDLAlmacen.Items.Count > 0 Then
If DDLAlmacen.Items.Contains(New ListItem("AlmacenDefectoAndes")) Then
DDLAlmacen.SelectedValue = "AlmacenDefectoAndes"
End If
End If
ListItem item = ddlComputedliat1.Items.FindByText("Amt D");
if (item == null) {
ddlComputedliat1.Items.Insert(1, lblnewamountamt.Text);
}
You could try checking to see if this method returns a null:
if (ddlCustomerNumber.Items.FindByText(GetCustomerNumberCookie().ToString()) != null)
ddlCustomerNumber.SelectedIndex = 0;
//you can use the ? operator instead of if
ddlCustomerNumber.SelectedValue = ddlType.Items.FindByValue(GetCustomerNumberCookie().ToString()) != null ? GetCustomerNumberCookie().ToString() : "0";
If the function return Nothing, you can try this below
if (ddlCustomerNumber.Items.FindByText(
GetCustomerNumberCookie().ToString()) != Nothing)
{
...
}
Sometimes the value needs to be trimmed of whitespace or it won't be matched, in such case this additional step can be used (source):
if(((DropDownList) myControl1).Items.Cast<ListItem>().Select(i => i.Value.Trim() == ctrl.value.Trim()).FirstOrDefault() != null){}

Categories