Xamarin Pass Entry Value to new page from old - c#

Hi i have a page where i get the user to fill out their fast name and last name and then when they hit the next button it performs an:
await Navigation.PushModalAsync(new VisitorHSAgreement());
to the next page, what I want to do is bring them values to display in a label on the next page I have currently tried this but it's coming back null can anybody help me.
public string VisitorFirstName { get; set; }
public string VisitorLastName { get; set; }
var visitorPage = new VisitorPage();
VisitorFirstName = visitorPage.FindByName<Entry>("FirstNameEntry").Text;

When on VisitorPage, there is an instance of the class VisitorPage. This instance contains controls, which are instances, too, and might have values set in their properties.
Now you navigating to VisitorHSAgreement and try to get a value from the VisitorPage by creating a new object of this class. Each object of this class comes with its own values and the controls are newly created. Unless you create some static field in VisitorPage you will never be able to access the values that are set in the first instance from the new instance. You should really read up on basic concepts of OOP, because this is really OOP 101.
I'd suggest to use MVVM along with the Prism library, this will really make your Xamarin.Forms life easier. Anyway, if you can't or don't want to at the moment (it's up to you in the end), there is still a solution. Since your properties are public, you can set them before navigating to VisitorHSAgreement
var page = new VisitorHSAgreement()
{
VisitorFirstName = FirstNameEntry.Text,
VisitorLastName = LastNameEntry.Text
};
await Navigation.PushModalAsync(page);

You need to learn how to work with Object Oriented programming.
As mentioned in the previous answer, you are trying to access empty values from a recently created object (which will obviously empty). While what you need to do is assign the values to the object you want to send, and then send that object (data filled in) to the page you want to use it.
Then in your page, receive that object sent from the previous page and explore its properties to obtain your values.

Related

Get all writeable properties of an ADLDS-Class

I'm developing an application which can deal with a MS-ADLDS-Service.
Currently it is possible to create Directory-Entries and assign values to some properties.
Not a realy exciting task until this:
Im my application it's possible (it should be) to configure which properties of a class (for instance: the CN=Person class) should be assigned with values which are evaluated at runtime in my application.
Long story short:
I want to retrieve all (writeable) properties of a class. Without creating and saving a new CN=Person-Object before.
Currently i use my schemaBinding to get the Directory-classSchema-Entry of the Person-Class (CN=Person) from where i read some property-values (like "AllowedAttributesEffective", "mayContain", "AllowedAttributes") - i get the most properties by this way - but some Properties are missing! For instance the "telephoneNumber"-Property (attributeSchema: CN=Telephone-Number)
Does anybody know how to get these properties of a class? ADSI-Edit does this: when i create a new object with adsi-edit i can assign values to all possible properties before committing the new entry.
thanks a lot for any hint!
(.net code is welcome)
I have found the solution for my task!
Some of these properties are "calculated" and not persistent at the directoryentry.
So its meant to call the RefreshCache() Method and pass the needed property names as an string array.
directoryEntry.RefreshCache(new string[] { "allowedAttributesEffective",
"allowedAttributes",
"systemMayContain",
"systemMustContain" });
After that call, the properties have values....
if (directoryEntry.Properties["systemMayContain"]).Value != null)
{
/// Success
}

How to maintain the values in view when i do postback in MVC

I have some controls in my page, when the page load first time the values are getting from database and placed in corresponding controls. When i click the another button again it will go to the controller and get the value from the database and bind the gridview. I have three class in my model, second and third class wrapped in first class. when i bind the second class in gridview, that time first class comes null so all the values are becoming null and bind the gridview only. How to solve this.
Again HTTP is stateless, unless you store your current model in a persistence medium like session, it will get lost in post back!
if I understood your question right !
when you bind your classes for the First Time , put them in a Session var then return it to the view ,
then when you post the second time when you click the other button, make sure to retrieve the session var in the actionmethod and then assign the new values to the class inside this session var, instead of just returning the new ones thinking that old ones are still there.
If I understand what you are asking then you can store it in TempData. TempData will persist until the next request.
public class YourView
{
public ActionResult Index()
{
string firstName = "Stephen";
TempData["FirstName"] = firstName;
return View();
}
public void ButtonClicked()
{
string firstName = (string)TempData["FirstName"];
}
}
Note though that temp data only lasts until the next request. So for this to work, after your view was loaded then the next call would have to be the ButtonClicked call.
The controller is stateless so if you need to persist something longer you have to make it kinda hackish and really ugly like this TempData["FirstName"] = TempData["FirstName"] in every spot that your controller will be called until you need to use that value. Like I said I don't recommend that (or for that case using Session) but if you needed to, then that's the safest way, in my opinion.

Pass data between pages in WP8 application

I am building a simple Sports Tracker application. I want to start a DispatcherTimer and a GeoCoordinateWatcher at Page 1, and in Page 2 I want a map view. And I am looking for the best practice how to pass the timers and the watchers value between pages, so I can show the updated information on the map.
I've seen suggestions to save it to an XML or into the IsoStorage. What is the best solution for this problem ?
Directly you can pass strings between your pages:
NavigationService.Navigate(new Uri("/destinationPage.xaml?dataKey="+dataValue.ToString()));
If you want to pass an object the first thing that hits is:
NavigationService.Navigate(new Uri("/destinationPage.xaml?dataKey="+dataObject.ToString()));
Here comes the problem:
1) You need to deserialize your object in your destination page. Or even worse,
2) Memory problem. Say you need to pass an image (captured in 41 mega pixel) and you are not allowed to use this much memory:
So here is another solution:
PhoneApplicationService.Current.State["yourparam"] = param;
Then you navigate to your destination page and you can access your object:
var k = PhoneApplicationService.Current.State["yourparam"];
Note: This thing would write your object in isolated Storage. So may be a bit slow.
Third option:
Use a static class to hold your dataValue between your pages. like:
static class Transporter
{
public static object container;
}
Now in your source page you can write:
Transporter.container = MyGeoCoordinateWatcherObj;
You can access this in your destination page. (here remains the problem of memory, but in your case you can use it safely.)
Note: Sometime microsoft recommends mvvm pattern to pass objects.

How does it work to use "Response.Redirect" from a Razor Web Page When I Haven't Instantiated "Response"?

My limited knowledge concerning programming entails that in order to use a non-static method, you need to first create an instance of the class. In order to use static methods, you simply use the Class name with the method name. I'm doing the WebPages tutorials for on asp.net and I came across the following code which confused me:
#{
var title = "";
var genre = "";
var year = "";
if(IsPost){
title = Request.Form["title"];
genre = Request.Form["genre"];
year = Request.Form["year"];
var db = Database.Open("WebPagesMovies");
var insertCommand = "INSERT INTO Movies (Title, Genre, Year) Values(#0, #1, #2)";
db.Execute(insertCommand, title, genre, year);
Response.Redirect("~/Movies");
}
}
I looked up the Redirect method of the Response class and it wasn't listed as static, which I'd assume to mean that it is an instance method. How am I able to use it without first creating an instance of the Response class?
Razor is a view engine plugin for ASP.Net MVC.
It does a number of things for you, such as on the fly code generation for your page views. What this means is that there is an underlying WebViewPage class attached to each of your pages which Razor automatically descends from and merges with the code you have in the #{ ... } sections.
This gives you access to several properties helpful for communicating with the browser such as Response, IsPost, Request, etc. I picked these three simply because they are in use in the code you posted.
So, for example, instead of writing code like MyPage.Response.Write("test!"); you can simply refer to the Response property of your page class directly. Exa: Response.Write("test!");
Razor is smart enough to know that Response is a property of the underlying class and uses it.
The Response property is an object of type HttpResponse. The response object has everything you need to write data (html for example) back to the client (browser).
The Request property is an object of type HttpRequest which gives you access to information sent from the client to your server. For example Request.Form is a collection of the html input control data (textboxes, radio, drop down lists...).
IsPost is a simple boolean which tells you if the page was a postback or the initial get.
The Response instance is created automatically by the webpages framework.
You are using razor, which is a view engine. For each view, a new class is generated, which derives from a base class. This base class has certain instance properties and methods, like Response, allowing you to use them in your view.
Response.Redirect(#href("~/Movies"));

C# - Get property in member class using Reflection

SHORT VERSION
What's the best way to use reflection to turn something like string prop = "part1.first_name"; into a System.Reflection.PropertyInfo, so that I can use the GetValue and SetValue functions?
LONG VERSION
I'm using ASP .NET MVC to build a questionnaire for my organization. It's very long, so it's divided into several different pages. Since it's not uncommon for us to get requests like, "Can you move this question to that page, and this other question to another page," I need to build this to be pretty flexible for a junior programmer to change.
My model is a complex class (it's got five member classes that have mostly primitive-typed properties on them).
So, I access it by doing things like Model.part1.first_name or Model.part2.birth_date.
Since the same model is used on all of the pages, but not all of the questions are on every page, I have ActionAttributes that essentially clear out all of the properties that were submitted on the form except for the ones that were displayed on that page (so someone can't inject a hidden field into the form and have the value persist to the database).
I want to make sure that I only save valid field values and don't let the user proceed to the next page until the current one is entirely OK, but I also want to save the values that are valid, even if the user isn't allowed to proceed.
To do this, I have a function that takes two instances of my model class, a reference to the ModelStateDictionary, and a string[] of field names like "part1.first_name" and "part2.birth_date". That function needs to copy all of the values listed in the string array that do not have validation errors from the first (ie, form-submitted) object into the second (ie, loaded from the db) object.
As stated above, what's the best way to use reflection to turn something like "part1.first_name" into a System.Reflection.PropertyInfo, OR, is there a better way to accomplish this?
var infoParts = prop.Split('.');
var myType = Type.GetType(infoParts[0]);
var myPropertyInfo = myType.GetProperty(infoParts[1]);
Assuming "part1" is your type. Although this is very limited and very dependent on the string being in the correct format and the type being in the current scope.
I would probably handle this differently, using data. I would keep, in the database, which step each question belongs to. To render that step, I would select the questions that match that step and have a model that contains a list of question id/question pairs. Each input would be identified by the question id when posted back. To validate, simply compare the set of question ids with the expected ids for that step. This way, to change which question goes in which step is to only change the data in the database.
If you do end up going down that road, you'll need to split the string into parts and recursively or iteratively find the property on the object at each step.
PropertyInfo property = null;
Type type = questionModel.GetType();
object value = questionModel;
object previousObj = null;
foreach (var part in questionId.Split('.'))
{
property = type.GetProperty(part);
previousObj = value;
value = property.GetValue(value,null);
type = value.GetType();
}
// here, if all goes well, property should contain the correct PropertyInfo and
// value should contain that property's value...and previousObj should contain
// the object that the property references, without which it won't do you much good.

Categories