I am probably missing something ready obvious. However, after trying to crack this all morning, I have gotten nowhere.
I am using Reverse Engineered Code First Entity Framework on my Web Form app.
I am attempting to update a submitted value before calling TryUpdateModel and can't seem to figure it out.
Here is my current code:
public void frmOrganisation_UpdateItem([RouteData] int id)
{
Website.Models.CrmOrganisation item = null;
var query = from o in db.CrmOrganisations
where o.OrganisationId == id
select o;
item = query.Single();
if (item == null)
{
// The item wasn't found
ModelState.AddModelError("", String.Format("Item with id {0} was not found", id));
return;
}
TryUpdateModel(item);
if (ModelState.IsValid)
{
db.SaveChanges();
Response.Redirect(Helper_Methods.AppendQueryStringToUrl("status", "Changes Saved!"));
}
}
One of the fields on the form is a textbox (id: txtWebsite) which is looking for a URL to be entered. I will be storing the full URL (http:// included) in the databse. However, I don't want users to have to enter the http://. Therefore, I want to intercept the value submitted and, if it doesn't start http, I want to prefix it. Only then do I want TryUpdateModel (and therefore validation) to occur.
Can anyone point me in the right direction?
Chris.
UPDATE - I've gotten alittle further.
Between my "TryUpdateModel" and "if (ModelState.IsValid)", I now have the line "if (ModelState["Website"] != null && !string.IsNullOrWhiteSpace(ModelState["Website"].Value.RawValue.ToString())) ModelState["Website"].Value = new ValueProviderResult("http://" + ModelState["Website"].Value.RawValue, "http://" + ModelState["Website"].Value.RawValue, CultureInfo.CurrentCulture);".
This is updating the model state, however, these changes are not being reflected in the database so I presume "db.SaveChanges();" is not seeing my change.
I've found a solution.
I'm updating the fields according on the OnClick event of the button that then issues the command to the update method. So, use clicks button --> OnClick event fires and updates form --> UpdateItem method gets called and updates the model and database.
Related
I'm trying to save the user data to the firebase realtime database directly after the user has been created. But the problem is not the saving, but the UserID. I save also save the user ID that i get from CurrentUser. and then i check in the realtime database and saw that the ID that stored was from a last user who recently created. And i check it in the editor by getting the current user Email and it showed the last user Email not the current user who are creating at the moment. Can someone help me to get the current user ID and not the last user id.
You guys can see the image from the links.
What ID should be
The last user ID showing up instead You guys can see that the ID don't event match. I did try redo the project and looking at the videos that from firebase it self. I really have no ide what to do, i am stuck for 3 days now.
public void SaveNewUserInCode(string userId, string Name, string Email) {
var currentUser = FirebaseAuth.DefaultInstance.CurrentUser;
string userNameId;
if (currentUser != null)
{
userNameId = currentUser.Email;
user = new User(userId, Name, Email);
string Json = JsonUtility.ToJson(user);
reference.Child("Users").Child(currentUser.UserId).SetRawJsonValueAsync(Json);
Data.text = userNameId;
}
}
It would be helpful to see the code that invokes SaveNewUserInCode.
I see a few potential dangers with the code you've posted:
The first is that any call (other than Auth.SignOut) is asynchronous. If you're caching userId immediately after Auth.SignInWithEmailAndPasswordAsync, you'll likely have the previous user still in Auth.CurrentUser (until the related task completes). See my related post on all the ways to wait for a task in Unity if you think this is the issue.
The second, especially if Email is sometimes null, you may be automatically calling Auth.SignInAnonymouslyAsync every time your app starts (perhaps old logic, I usually start my prototypes with anonymous users and later on add real accounts when it's time to do some user testing). This will always overwrite your current user even if you were previously signed in anonymously. You should always check Auth.CurrentUser before calling any of the Auth.SignIn methods, but definitely make sure that you don't have a stray Auth.SignInAnonymouslyAsync laying around.
If the issue is threading, I believe the following logic will fix your problem:
var auth = FirebaseAuth.DefaultInstance;
auth.SignInWithEmailAndPasswordAsync(email, password).ContinueWithOnMainThread(task => {
// omitted : any error handling. Check task's state
var user = task.Result;
SaveNewUserInCode(user.UserId, user.DisplayName /* or however you get Name */, user.Email);
});
In my application, i am storing an object into session which is passed to a web service to return data to display in a table. If the session exists, then it will not ask the user to input fresh data. However, if a user selects a link called "New List", then the session data will be cleared and the user prompted to enter new data.
In my code, i have an anchor defined like so:
New List
Which will trigger this Controller Action:
public ActionResult NewList()
{
Session["new_list"] = "y";
return RedirectToAction("List");
}
And then continue to execute this action:
public ActionResult List()
{
if ((string)Session["new_list"] == "y")
{
//clear session variables, load fresh data from API
}else{
//display blank table. Ask user to input data to retrieve a list
}
....
}
Now, the issue i have is when a user navigates away from the list page, and then navigates back with the browser's back button, it is still calling newlist. In the history of the browser, instead of storing List it is storing newlist which is causing the session variable to clear. What can i do to stop this from happening or is there a different mechanism to use in c# mvc that can help me achieve the desired effect.
Your main problem here is that the NewList action uses GET when it should really be a POST.
A GET request is never supposed to alter the state of a resource, but simply return the current state of the resource; while a POST request allows for the altering of a resource.
Because you allow the NewList action to be called with a GET request, the user's browser assumes (quite rightly on its part) that nothing bad/undesired will happen if it simply repeats the request in the future, e.g. when a user uses the back button.
If instead a POST request is issued, a user browser will never re-issue the request without the user confirming they actually intended to re-issue it.
The solution to your problem then is modify this to the standard PRG pattern: POST/Redirect/GET; that is, send a POST request to perform the state change, redirect the user browser to another page, and GET the result page. In this scheme, pressing the back-button would effectively "skip" over the state change action and go the previous page the user was on.
To accomplish this in MVC:
[HttpPost]
public ActionResult NewList()
{
//clear session variables, load fresh data from API
return RedirectToAction("List");
}
public ActionResult List()
{
// whatever needs to happen to display the state
}
This does mean that you can't provide the "New List" action directly as a hyperlink in the page, as these will always issue GET requests. You will need to use a minimal form like so: <form method="post" action="#Url.Action("NewList", "Alert")"><button type="submit">New List</button></form>. You can style the button to look like a normal hyperlink as desired.
The reason it storing NewList is because you are redirecting to "Alert/NewList", and its the string in your URL for making hit to "NewList" Action, So whenever you are try back button the browser gets this "Alert/NewList" URL, hence its making hit to action "NewList".
But now, I am not getting why the session gets clear. because you are initializing the session in "NewList" itself. Still i suggest you to use local-storage to assign values with session.
In MVC, the default views for a controller allow one to reach the edit page via selecting an item in an index and using that id to reach the specific edit page.
In this MVC edit page, I have a javascript that reacts to a change in a dropdown. The dropdown represents a subset of the potential id's available from the index page, and in general, someone will choose a different one than the currently displayed one.
The postback to the control works correctly in C#, and I can find the relevant model that goes with the id. It all appears correct on the C# controller side. However, when I try to get it to redirect back to the same edit page but with a different id (that from the dropdown), the page reverts back to the ajax call.
Is there anyway to "short-circuit" the ajax call so that it "knows" that it doesn't return but lets the C# redirect to the edit page (just like what happens when an element is chosen from the index page).
Thanks in advance,
Joseph Doggie
If you are making ajax requet, then you have to implement a way to redirect.
Depends on your ajax protocol... Are you returning json? html ...
If returning json, you could add a flag in your response telling wether this is a redirect answer and do redirect in js :
window.location = url
OK, there is at least one way to do this.
Assume editing X with Controller named YController:
JavaScript:
var MyControllerUrlSettings = {
MyControllerPrepareModifyXInfoUrl: '#Url.Action("PrepareModifyAssetInfo", "Y", new { x_txt = "param" })'
}
one then has a JavaScript to handle the dropdown change:
$('#ModelXList').change(function () {
//// alert('Change detected');
if ($("#ModelXList").val() != "") {
//// alert('Reached here');
var XNbrString = $("#ModelXList").val();
var trimmedXNbrString = $.trim(XNbrString);
//// debugger;
if (trimmedXNbrString != "") {
var url = MyControllerUrlSettings.MyControllerPrepareXInfoUrl;
window.location.href = url.replace('__param__', trimmedXNbrString);
}
}
else {
}
});
Finally, in the controller, there is a method:
public ActionResult PrepareModifyXInfo(string XNbr_txt)
{
// we cannot save anything here to cdll_cdcloanerlist;
// static variables must be used instead.
/// .... do what you have to do....
return RedirectToAction("ModifyEdit", new { XNbr_txt = XNbr_txt });
}
Note: For proprietary reasons, I changed some of the syntax so that everything would be general, therefore, you may have to work with the above code a little, but it works
Alternate answers are really welcome, also!
I have a login page that authenticates to AD, works great. After login there is a page for a service request, user can save their request and return to it later to finish or submit it if it's done. These 2 actions set a flag in the record (saved or submitted). When a user logs in, I can present them with a list of their saved requests. Now, if they click on a saved request link, I can pass the record ID via the URL.... but then I get stuck.
Should I have a different page for editing/updating records, or should I use the new request page again? If I use the same page, what's the best way to do that? My impression is that there would be a lot of "if...returning...else", making the code difficult to read. On the other hand... if I do 2 pages, any change or update needs to go in both.
I'm using VS2010 and EF4. First project in this environment, don't know what's best practice here.
I'm a fan of reusing the page; there is some if/else, but not all over the place. For instance, when updating an entity, you can do:
SomeEntity entity;
bool adding = false;
if (key > 0)
entity = db.Entities.FirstOrDefault(i => i.Key == key);
if (entity == null)
{
entity = new SomeEntity { initialvalue = "X" };
adding = true;
}
entity.Z = someValue;
//set other props
if (adding)
db.Entities.AddObject(entity);
db.SubmitChanges();
As far as the UI is concerned, yes there is some showing/hiding, but effort-wise there will be less.
I am wondering How i can keep the text of my textbox even if i have to make a new page load, clicking on an hyperlink.
It's always an empty string.
Can someone help me ?
lkForgotten.NavigateUrl = string.Format("Logon.aspx?forgotten={0}", "");
lkSend.NavigateUrl = string.Format("Logon.aspx?forgotten={0}&userEmail={1}", "submited", txtForgotten.Text);
try
{
if (Request.QueryString["forgotten"].ToString() == "")
{
txtForgotten.Visible = true;
lkSend.Visible = true;
}
if (Request.QueryString["forgotten"].ToString() == "submited")
{
userEmail = txtForgotten.Text;
SendForgottenPassword(userEmail);
}
}
catch { }
If you need to persist some data specific to the person, you can use a session. It is precisely the thing you need.
You can set it whenever you want and get the values you need.
http://msdn.microsoft.com/en-us/library/ms178581.aspx
Edit:
To satisfy some objections raised in comments, if the session itself isn't enough, you can still use a different approach. Monitor the textboxes with javascript and if their value is changed, add a cookie (or add a value to existing cookie, depends on the needs). Still much better approach than using querystring for this type of functionality... At least in my opinion.
Edit
Do the redirection with the
Javascript code
function redirect()
{
var val = document.getElementById('<%= txtForgotten.ClientID %>').value;
location.href='Logon.aspx?forgotten=submitted&userEmail=' + val ;
}
<input type="button" VALUE="Visit Microsoft" OnClick="redirect();">
problem witht he above code is when you are creating the url of forget password on page load at that time textbox value is empty and when do redirection by clicking forget password link its getting empty value only rather what you typed in your code...so to make it work do the redirection using javascript as above or make use of click event that do the redirection for you....
Org
following line change like this
if (Request.QueryString["forgotten"].ToString() == "submited") {
userEmail = txtForgotten.Text = Request.QueryString["userEmail"].ToString() ;
SendForgottenPassword(userEmail);
}
so when you are clicking button it get the value of userEmail from the querystring and restore value in you textbox ...this will surely do your task
or
you can make use of other client side mecanisam like cookies to store the value and than retrive it back on page...
serverside option is session variable also helpfull if you want to store the value and retrieve it back.....