Convert object to a string c# xamarin forms - xamarin.forms

I want to convert a label value (Object) to a string variable but I get an empty string.
Here is the code.
var label = new Label
{
};
label.SetBinding(Label.TextProperty, "Link");
string url = label.GetValue(Label.TextProperty).toString();
I want to use the content of the label as a string.
If I don't convert it the url in the label it's ok but when I convert it I get an empty string as result. Any help? How can I convert this to a string?
Thanks in advance.

You can set the Label text implicitely, but I have a feeling that's not what you're trying to do.
If you want to bind to a Link property from a ViewModel, you probably just forgot to set the BindingContext for your Label.
var label = new Label
{
Text = "Set implicitely"
};
string url = label.GetValue(Label.TextProperty).ToString(); // Set implicitely
MyViewModel viewModel = new MyViewModel
{
Link = "Set through binding"
};
label.BindingContext = viewModel;
label.SetBinding(Label.TextProperty, "Link");
string url2 = label.GetValue(Label.TextProperty).ToString(); // Set through binding

Well I found a very easy solution as #hichame.yessou already mentioned on the first comment.
I was passing data into a label by XAML
<Label Text="{Binding Link}" x:Name="linkLabel" IsVisible="False" />
But I put the "x:name" property in order to handle the label from the xaml.cs file.
Well then all was easy..
string url = linkLabel.Text;

Related

How to get the selected value from a dropdown in MVC to use inside the view

I have an MVC app with leaflet running in it, I am parsing xml data to get the paths to the leaflet tiles which I then display in a drop down via a ViewData["value"]. The problem is I can't seem to figure out how to get that selected value and pass it down to the leaflet js as a path and then display everything. I tried many different ways to get the selection data but I'm just hitting a wall again and again.
The below code is how I send it to the view. I display it via an #Html.DropDownList("layerType", ViewData["value"] as List)
string outputPath;
outputPath = ConfigurationManager.AppSettings.Get("outputPath");
XmlDocument xDoc = new XmlDocument();
xDoc.Load(outputPath + #"\log.xml");
XmlNodeList layerType = xDoc.GetElementsByTagName("layerType");
XmlNodeList layerPath = xDoc.GetElementsByTagName("layerPath");
XDocument doc = XDocument.Load(outputPath + #"\log.xml");
var count = doc.Descendants("layers")
.Descendants("layerData")
.Count();
List<SelectListItem> li = new List<SelectListItem>();
foreach (int i in Enumerable.Range(0, count))
{
li.Add(new SelectListItem { Text = layerPath[i].InnerText, Value = i.ToString() });
}
ViewData["value"] = li;
return View(li);
How would I get the selected data and simply pass it down into the leaflet part inside the js tags.
Would I maybe pass it back into a controller and then back to the view?
#Html.DropDownList("layerType",
new SelectList((IEnumerable) ViewData["value"]), "Value", "Text")
In the Post method, you have to fill the viewdata again to avoid error if model returns invalid
Refer Below Link :
MVC Select List with Model at postback, how?
Working Code
https://dotnetfiddle.net/2lrb2S
Get Value on View
<script>
var conceptName = $('#nameofyourdropdowncontrol').find(":selected").text();
//code for passing value
</script>

HTML Select control does not have selected value when generated with Razor DropDownListFor

I have a view in asp.net/mvc4/razor application where I want to edit value of model using dropdownlist control. I use it this way:
#Html.DropDownListFor(m => m.DateFormat, new SelectList(new [] {"mm/dd/yyyy", "dd/mm/yyyy"}))
The value of DateFormat property is set to one of those values in model but when I load the view, the html select is always set to first value. Am i missing sth?
UPDATE:
This was driving me nuts for two days. Finally I changed the name of property and it started to work. I think it somehow conflicted with value I stored in ViewData/ViewBag collection under the same key. I am not yet sure why. Maybe somebody can explain that?
Try your SelectList something like this where you define the text and the value, along with the selected item.
#(Html.DropDownListFor(m => m.DateFormat, new SelectList
(
new List<Object> {
new {
value = "mm/dd/yyyy", text = "mm/dd/yyyy"
},
new {
value = "dd/mm/yyyy", text = "dd/mm/yyyy"
}
}, "value", "text", Model.DateFormat)
))
This code is untested
Make the SelectList a buddy property of the model.
public class MyModel(){
prop DateTime MyDate {get;set;};
prop SelectList SelectDates {get;set;}
}
Then populate the SelectList after you have selected your date (remember to do this every time you build your model):
SelectDates = dates.Select(d => new SelectListItem
{
Value = d.ToString(),
Text = d.ToString(),
Selected = d == MyDate
})
Then use the property when you build your dropdown:
#Html.DropDownListFor(m => m.DateFormat, Model.SelectDates ))

adding url to the hyperlink field in gridview

I have a dynamic grid view. I add column in page load.
I use this code for add Hyperlinkfield :
string[] url = new string[1];
url[0] = field.InternalName;
HyperLinkField link = new HyperLinkField();
link.HeaderText = field.Title;
link.DataNavigateUrlFields = url;
link.DataNavigateUrlFormatString = "{0}";
link.DataTextField = field.InternalName;
link.SortExpression = field.InternalName;
grid.Columns.Add(link);
my problem is : for example my url is "http://Test1.docx, http://Test1.docx".
I want navigateurl set "http://Test1.docx" .
If I am understanding correctly what the issue is. The field.InternalName field contains "http://Test1.docx, http://Test1.docx" to which you are assigning to a string array and you are trying to attempt to only get the first value before the comma.
In that case, you will need to split the string:
string[] urlSplit = field.InternalName.Split(',');
link.DataNavigateUrlFields = urlSplit[0];

Custom helper for generating html tags for radio button and associated label

I was searching for a solution about radio buttons and associated labels. I like the way we can select each radio button by clicking on the label associated. By default, this doesn't work very well. I mean the labels are not correctly associated with radio buttons.
Example: let's say we have a property named Revoked with possible values Yes/No. We would like to use radio buttons to let the user choose the value.
The problem: when html tags are generated from MVC (Html.LabelFor, Html.RadioButtonFor), the ID of both radio buttons (Yes/No) are the same. Thus it is impossible to associate each label with the corresponding radio button.
The solution: I created my own custom helper for generating html tags with correct and unique ID.
Here is my helper:
public static MvcHtmlString RadioButtonWithLabelFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object value, object labelText)
{
object currentValue = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model;
string property = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).PropertyName;
// Build the radio button html tag
TagBuilder htmlRadio = new TagBuilder("input");
htmlRadio.MergeAttribute("type", "radio");
htmlRadio.MergeAttribute("id", property + value);
htmlRadio.MergeAttribute("name", property);
htmlRadio.MergeAttribute("value", (string)value);
if (currentValue != null && value.ToString() == currentValue.ToString()) htmlRadio.MergeAttribute("checked", "checked");
// Build the label html tag
TagBuilder htmlLabel = new TagBuilder("label");
htmlLabel.MergeAttribute("for", property + value);
htmlLabel.SetInnerText((string)labelText);
// Return the concatenation of both tags
return MvcHtmlString.Create(htmlRadio.ToString(TagRenderMode.SelfClosing) + htmlLabel.ToString());
}
It works but I need advise. What do you think? Is it efficient? I'm still new to the world of ASP.NET MVC so any help is greatly appreciated.
Thanks.
Other than some minor improvements that could be made the helper looks fine:
You don't need to call ModelMetadata.FromLambdaExpression twice with the same arguments
In order to generate the id you are concatenating the property name with the value but this value could contain any characters while an id in HTML allows only certain characters. You need to sanitize it.
You are casting both the value and currentValue to strings which might fail if the helper is used on some other property type. In this case either make the helper work only with string properties by reflecting on the helper signature or use Convert.ToString().
Here's the refactored version which takes into account those remarks:
public static IHtmlString RadioButtonWithLabelFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
TProperty value,
string labelText
)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
object currentValue = metadata.Model;
string property = metadata.PropertyName;
// Build the radio button html tag
var htmlRadio = new TagBuilder("input");
htmlRadio.GenerateId(property + value);
htmlRadio.Attributes["type"] = "radio";
htmlRadio.Attributes["name"] = property;
htmlRadio.Attributes["value"] = Convert.ToString(value);
if (object.Equals(currentValue, value))
{
htmlRadio.Attributes["checked"] = "checked";
}
// Build the label html tag
var label = new TagBuilder("label");
label.Attributes["for"] = htmlRadio.Attributes["id"];
label.SetInnerText(labelText);
// Return the concatenation of both tags
return new HtmlString(
htmlRadio.ToString(TagRenderMode.SelfClosing) + label.ToString()
);
}

Convert a string to value of control

I have a string str = "txtName.Text" (txtName is name of textbox control)
How to display value of textbox without is value of string str (use C#)
Let me a solution.
Thanks a lot !
Probably the easiest thing to do would be to extract the control id like this:
String controlId = str.Substring(0, str.IndexOf('.'));
Then use the Page.FindControl method to find the control and cast that as an ITextControl so that you can get the Text property value:
ITextControl textControl
= this.FindControl(controlId) as ITextControl;
if (textControl != null)
{
// you found a control that has a Text property
}
I assume that the question is: How to get value of textbox control given its ID as a string.
Use FindControl method.
Example:
TextBox myTextBox = FindControl("txtName") as TextBox;
if (myTextBox != null)
{
Response.Write("Value of the text box is: " + myTextBox.Text);
}
else
{
Response.Write("Control not found");
}
If by "value" you mean "numeric value", then you can't - text boxes contain strings only. What you can do is get the string like you did, and parse that string into a number.
You can use int.Parse() or double.Parse() (depending on the type), or TryParse() for a safer implementation.

Resources