How to pass and get the parameters from one viewmodel to another viewmodel in wph8.1 i am using INavigationService like below but i don't know how to get the parameters from another viewmodel.
_Navigate.Navigate(typeof(nextView),data);
You can use Messenger to pass data between the view-models. Messenger is intented for it.
To send a message:
MessengerInstance.Send(payload, token);
To receive message
MessengerInstance.Register<PayloadType>(
this, token, payload => SomeAction(payload));
View model 1
MessengerInstance.Send(Brushes.Red, MessengerToken.BrushChanged);
View Model 2
class ViewModel()
{
// put this line in the constructor
MessengerInstance.Register<Brush>(this, token, brush => ChangeColor(brush))
}
//Receive here
public void ChangeColor(Brush brush)
{
Brush = brush;
}
Related
I want to send some data when user clicks on this link
<a asp-action="ViewOthersProfile">#question.Questionaire</a>
and this is my action method
[HttpGet]
public ViewResult ViewOtherProfile()
{
return View("OtherProfile");
}
also,how we'll get it in action method. Thanks in advance
//Use asp-route-myData for your data and you can name it whatever you want.
//asp-route-myData2, asp-route-data, asp-route-dog, ... you got the point.
<a asp-action="ViewOthersProfile" asp-route-myData="test string">#question.Questionaire</a>
//Here you can get your data as a parameter.
//However, the parameter name must be the last part of asp-route-myData. I mean 'myData'
[HttpGet]
public ViewResult ViewOtherProfile(string myData)
{
//And you can use myData whatever way you need
var result = myData + "test2";
return View("OtherProfile");
}
I'm just starting the ASP.NET tutorial and I don't understand why there is no return statement in the method:
public async Task OnGetAsync()
{
Movie = await _context.Movie.ToListAsync();
}
Are one line methods automatically returned like arrow statements or does it have to do with the Task in ASP?
Its a model that have property Movie. That property gets set when method OnGetAsync is called. So, you don't need return.
Method return type is Task because it has await. Its analogous to void type if it would be a sync method.
if you want to return the list of Movie
then your function should be :
public async Task<List<Movie>> OnGetAsync()
{
return await _context.Movie.ToListAsync();
}
If there is one controller yii2 with one model in which, for example, the outline only:
class MyController class extends Controller {
public function actionCreate() {
$valid = $model->validate();
}
}
Need the return from aftersave, which is a message indicating if the email was able to be sent or not, and all the attributes were inserted.
afterSave in the model:
public function afterSave($insert, $changedAttributes) {
if(!$this->isNewRecord) {
try {
Yii::$app->mailer->compose()
// email composition here
->send();
return 'mail sent';
catch (\Swift_SwiftException $exception) {
return 'email undeliverable'. $exception->getMessage();
}
}
}
Can the return from afterSave be accessed by the controller?
No, you will not be able to access any of those messages, because:
In the controller you are calling $model->validate() and afterSave() will never be called. You would need to call $model->save().
afterSave() is not supposed to return anything, so the value you are returning is lost. See the function definition in the official documentation here
No, it's not gonna trigger the afterSave event with your code. \yii\db\BaseActiveRecord::afterSave is being triggered in 2 places
\yii\db\BaseActiveRecord::updateInternal
\yii\db\ActiveRecord::insertInternal
and if you take a look at \yii\base\Model::validate you'll see that afterSave isn't calling in here.
See this :
#Html.ActionLink("link", "Func", new { controller = "MyControl" }, new { target = "_blank" })
It does what it is suposed to do, but what if i need my model, because here is the header of my function :
public ActionResult Func(model_1 m)
{ }
What i'm trying to do is open a new tab, and carry my model to this new tab... how can i do?
There is an overload of Html.ActionLink helper method which allows you to pass route values.
#Html.ActionLink("link", "Func", "MyControl" ,new { EmpId=1, EmpCode="E23" ,Age =23},
new { target = "_blank" })
This will basically generate an anchor tag with href value with querystring formed from the route values you provided.
link
Assuming you have a class with these 2 properties being used as the parameter of the action method
public class EmployeeVm
{
public int EmpId { set;get;}
public string EmpCode { set;get;}
public int Age{ set;get;}
}
and this is being used as the type of your action method argument
public ActoinResult Func(EmployeeVm model)
{
// To do : Return something
}
The model binder will be able to map the querystring values to the properties of the parameter object.
But remember, querystring's has limitations in how much data it can carry. Also the above approach work for a lean-flat view model class. It won't work for a complex viewmodel class where your properties are other classses /collection of other types.
In that case, The best solution is to pass a unique id / combination of Ids and use that to rebuild your model / view model in the second action method.
#Html.ActionLink("link", "Func", "MyControl" ,new { EmpId=1}, new { target = "_blank" })
and in your action method
public ActionResult Func(int empId)
{
// to do : Using empIdvalue, Get the View model /Model data
// Ex : EmployeeVm emp = SomeService.GetEmployeeFromId(empId)
}
Assuming SomeService.GetEmployeeFromId accepts an employeeId and return an object of EmployeeVm. The method can query your db table to get the corresponding employee record for the id passed in and build the EmployeeVm object from that data.
Is there a way to authenticate a user through Facebook in mvvmcross framework? I'm currently attempting use Mobile Azure Service to authenticate to Facebook, but I don't have any success. Without using mvvmcross, I can authenticate just fine.
Thank You!
Mark
In the MVVM sense what I've found is that no, you can not. Properties on the facebook login page are not bindable, nor should they be and is best treated as a modal view out of your control
What I would do is make it a view concern and use Xamarin.Auth to authenticate.
As an example let's say that you had a LoginView and LoginViewModel.
The LoginView provides your standard login Email/Password but with an option (button) to authenticate via facebook
From that view hook up to the touchupinside event of the facebooklogin button
this.btnFacebookLogin.TouchUpInside += (object sender, EventArgs e) =>
{
DoFacebookLogin ();
}
Then in your DoFacebookLogin method 'present' the viewcontroller for facebook as described here https://github.com/xamarin/Xamarin.Auth/blob/master/GettingStarted.md
For example :
private void DoFacebookLogin ()
{
var auth = new OAuth2Authenticator (
clientId: "yournumericclientidhere",
scope: "",
authorizeUrl: new Uri ("https://m.facebook.com/dialog/oauth/"),
redirectUrl: new Uri ("http://www.facebook.com/connect/login_success.html"));
auth.AllowCancel = true;
auth.Completed += (sender, eventArgs) => {
DismissViewController (false, null);
if (eventArgs.IsAuthenticated) {
string user = eventArgs.Account.Serialize ();
var messenger = Mvx.Resolve<IMvxMessenger> ();
messenger.Publish (new FacebookLoggedIn (user));
} else {
// Cancelled here
}
};
var vc = auth.GetUI ();
this.PresentViewController (vc, true, null);
}
Cancelled does not need to be handled since the modal viewcontroller will take you back to your LoginView
On success that viewcontroller is dismissed then I would use mvx's interpretation of an eventaggregator (plugins.messenger) to send a message to the viewmodel that the facebook modal view is closed, with that message you can pass the account details - accesstoken etc back to the viewmodel to do as you wish.
View (as above) :
string user = eventArgs.Account.Serialize();
var messenger = Mvx.Resolve<IMvxMessenger> ();
messenger.Publish (new FacebookLoggedIn (user));
Message Class in your PCL :
public class FacebookLoggedIn : MvxMessage
{
public FacebookLoggedIn(object sender) : base(sender) {}
}
ViewModel also in your PCL :
public LoginViewModel()
{
var messenger = Mvx.Resolve<IMvxMessenger> ();
user = messenger.SubscribeOnMainThread<FacebookLoggedIn> (OnFacebookLoggedIn);
}
private void OnFacebookLoggedIn (FacebookLoggedIn MvxMessage)
{
... do something with the accesstoken? call your IUserService etc
ShowViewModel<MainViewModel> ();
}
Since you're dismissing the facebook viewcontroller you'll find yourself back on the loginview momentarily before automatically navigating to the MainView
In your view project you need to ensure the plugin is loaded otherwise you'll receive an error during construction of the viewmodel, so in setup.cs
protected override void InitializeLastChance ()
{
Cirrious.MvvmCross.Plugins.Messenger.PluginLoader.Instance.EnsureLoaded();
base.InitializeLastChance ();
}
Additionally you can also store the account credentials locally, this is described on the Xamarin.Auth link under AccountStore.Create().Save. Note that if you receive a platform not supported exception then add PLATFORM_IOS as a preprocessor directive to your project.
I realise the question is a couple of months old but since it rates high on google thought I'd provide an answer since there isn't any