Form-Methode Get works fine but Post doesn't work

Hallo,

i'm trying to write a login for my application. i need to get the username and password from a form. so i tryed this:

<%using (Html.Form("Login", "Login", FormMethod.Post)) { %>
        User name: <%=Html.TextBox("userName", new {type="text", value = ""}) %>
	Password:  <%=Html.TextBox("password", new {type="text", value = ""}) %>
	<%=Html.Hidden("returnUrl", new {value ="test.url"} )%>
	<%=Html.SubmitButton("submit", "Login")%>
<%} %>
 if i try this with GET it works but POST doesn't work? the controller action is called correctly but the Request.Form is completly empty.

does sombody know what i'm doing wrong?
0
saijado
7/9/2008 8:46:46 PM
asp.net.mvc 4300 articles. 0 followers. Follow

15 Replies
1109 Views

Similar Articles

[PageSpeed] 42

Looks OK to me, someone else may spot the problem.  Your page could be simpler, something like

<% using (Html.Form("Login", "Authenticate", FormMethod.Post)) { %>
   User name: <%=Html.TextBox("userName") %>
   Password: <%=Html.Passwod("password") %>
   <%=Html.Hidden("returnUrl", "test.url") %>
   <%=Html.SubmitButton("submit", "Login")%>
<% } %>

 The Html.TextBox helper generates a control with type="text" so you don't have to specifiy it.  The value should be blank as well so you don't need that.  Probably better to use the Html.Password helper for your password box so that an entered password is obscured from onlookers.  Html.Hidden has an override which takes the value as a string for its second parameter.  You contoller action, given the default route, would just need to be

public ActionResult Authenticate(string userName, string password, string returnUrl)
{
   if (IsValid(username, password)) ...

   return Redirect(returnUrl);
}

 If you are still having problems you may need to post you controller action code.

hope that helps


Got a c# problem? Try .NET Book Zero from Charles Petzold, it's a free pdf.
0
Paul
7/10/2008 12:47:38 AM

 ok i've changed the aspx to this:

        <%using (Html.Form("Login", "Login", FormMethod.Post)) { %>
            User name: <%=Html.TextBox("userName") %><br />
            Password:&nbsp; <%=Html.Password("password") %><br /><br />
            <%=Html.Hidden("returnUrl", new {value = "test.url"} )%>
            <%=Html.SubmitButton("submit", "Login")%>
        <%} %>

 but this should not be the the problem. the first site was just an experiment to setup the login.

here is the controller action:

 

public ActionResult Login(string userName, string password, string returnUrl) {
if (this.IsValidLoginArgument(userName, password)) {
if (Membership.ValidateUser(userName, password))
this.RedirectFromLoginPage(userName, returnUrl);
else
this.ViewData["LoginFaild"] = "Login faild! Make sure you have entered the right user name and password!";
}
return View("Login");
}
 
0
saijado
7/10/2008 6:39:53 AM

There is definitely no reason why the form collection would be empty. Can you confirm that you are using MVC Preview 3 and do not have 3.5 SP1 installed?

In addition to Paul's advice, I would recommend checking that your HTML is valid. If you have any overlapping tags, it could prevent the data from being submitted to the correct form.

As a side note, there is no need (or standard practice) to use an Html overload for something that is not dynamic. In your case, you can still use <input type="submit" value="Login" /> for your submit button. There is nothing wrong with using Html.SubmitButton, of course, but it does add more code clutter to the view.

0
richard
7/10/2008 6:42:31 AM
I just had a thought, the other reason you may have no data is if something is performing a redirect (form data is lost on a redirect). Set a breakpoint in your action and check if the http method is POST, if it is GET then something is redirecting you.
0
richard
7/10/2008 6:48:24 AM

Just to be sure, to be sure.  Can you put a breakpoint on the first line of your action "if (this.IsValidLoginArgument(userName, password)" and double check that the parameters to the function are null, because this really should work.


Got a c# problem? Try .NET Book Zero from Charles Petzold, it's a free pdf.
0
Paul
7/10/2008 7:11:54 AM

 This is the form code I use, which has a correct tag semantics too (fieldset, associated labels, etc). And it works just fine.

 <% using (Html.Form<HomeController>(c => c.Login(null, null)))
       { %>
        <fieldset>
            <legend>Login private area</legend>
            <div>
                <label for="username">Username</label>
                <%= Html.TextBox("username") %>
            </div>
            <div>
                <label for="password">Password</label>
                <%= Html.Password("password") %>
            </div>
            <%= Html.SubmitButton("submit", "Login") %>
        </fieldset>
    <% } %>

 And then the action method is really simple

 public ActionResult Login(String username, String password)
        {
            //Your code here
        }


Matteo Mosca
Web Developer
IWA Member
0
Sgro
7/10/2008 7:44:15 AM

 If I remember right the http method is set to GET in the request object but its set to POST in the HTML code.

 it's a redirect from the default site. but calling login from the login site should be no redirect.

 
the steps are:

1. accessing the default

2. redirect to the login method with parameters = null

3. render login view

4. calling the login method with login parameters

 

the first calling is a redirect but the second shoul be no redirect. but how can i solve this problem?

best regards and thanks for your fast answers
 

0
saijado
7/10/2008 7:54:25 AM

Your initial redirect from default is irrelevent. Basically, it should be like this:

1. GET /Login (LoginController.Login, no parameters)

2. Render login view

3. POST /Login (LoginController.Login, with parameters)

I think that #3 is somehow redirecting back to GET /Login. I recommend installing something like Fiddler for IE (http://www.fiddlertool.com/Fiddler2/version.asp) or Charles for Firefox (http://www.charlesproxy.com) and seeing if you are indeed being redirected (no point in going deep without checking if that's actually the problem).

0
richard
7/10/2008 8:05:45 AM

i will check it this evening 

0
saijado
7/10/2008 10:33:48 AM

ok i've checked it with charles. and there i can see that after pushing the login button the POST is send. but it don't reaches the controller. directly after the POST there is a GET to the same controller method and this one reaches the controller. is this a redirect? how can i prevent this?

0
saijado
7/10/2008 7:46:00 PM

What is the status code returned from the POST to your controller? If it is 301 or 302 that means a redirect. From your description this looks like the case.

Is anything causing a redirect (other than a successful login)? Do you have any GET constraints on the route?

If the above doesn't help, post the code to your route table and controller. Are you using any action filters or custom http modules?

Richard

0
richard
7/10/2008 9:20:01 PM

 the status code is 302 so it is a redirect. i don't know if i have some special GET constraints. the routing table is the standard routing table:

public static void RegisterRoutes(RouteCollection routes) {
	routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
	routes.MapRoute(
	    "Default",                                              // Route name
	    "{controller}/{action}/{id}",                           // URL with parameters
	    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
	);
}
here is the controller action. the if clause is never true because the parameter and the request.form is always null/empty 
public ActionResult Login(string userName, string password, string returnUrl) {
	if (this.IsValidLoginArgument(userName, password)) {
		if (Membership.ValidateUser(userName, password))
			this.RedirectFromLoginPage(userName, returnUrl);
		else
			this.ViewData["LoginFaild"] = "Login faild! Make sure you have entered the right user name and password!";
	}
	return View("Login");
}
the http modules schould be the standard which are in the webconfig when you starting a new mvc project. i don't use actionfilter.
this is the only thing i've added to the webconfig:
<authentication mode="Forms">
	<forms loginUrl="Login/Login/"  defaultUrl="Home/Index/"/>
</authentication>
<authorization>
	<deny users="?"/>
</authorization>
<membership defaultProvider="NHMemberShipProvider" userIsOnlineTimeWindow="15">
	<providers>
		<clear/>
		<add name="NHMemberShipProvider" type="WebLib.NHMemberShipProvider" applicationName="Portal" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" passwordFormat="Encrypted"/>
	</providers>
</membership>
  

best regards

Saijado

0
saijado
7/10/2008 10:15:57 PM

 sorry double post

0
saijado
7/10/2008 10:17:13 PM

Ah, I think I see it.

Your login url in the web.config needs to match the url that the routetable generates EXACTLY. In your charles log, is the POST url and the followup GET url exactly the same? My guess is that the POST url has no trailing slash and the redirect url does. Remove the trailing slash from the loginUrl="" attribute in your config and that should fix things up.

Richard

0
richard
7/11/2008 6:39:26 AM

 yes you were completly right with the slash. i diddn't know that the frame work is so fussy with the urls.

 thanks a lot for your help

 

best regards

Saijado

0
saijado
7/11/2008 4:25:46 PM
Reply:

Similar Artilces:

TempData doesn't work with GET and POST decorated methods
 On the project that we are working, we are using MVC Privew5. We have problem with sharing TempData between methods decorated with GET and POST.For instance:[AcceotVerb("GET")] public ActionResult Test(){ TempData["Test"] = "Error";}  [AcceotVerb("POST")] public ActionResult Test(FormCollection form){  string test = TempData["Test"]; }  In the second method decorated with POST TempData will be null ... Is there any solution, workaround? Thanks/Todor Hi This works under RC1 of MVC. Please u...

Spellchecker doesn't work: no error, just doesn't work
Hey all. This is only happening with one person. It's all GW7 no SP. has worked fine before. Anyway when they type along it doesn't catch that spelling and it doesn't fire up spell check before it's sent like it is checked off to do. It does nothing. It just sends it when you click send; no error, nothing. I did a rebuild, analyze/fix. I have it set at all levels for this user. any ideas Mark, well, I'd try a more recent client version first. GW7 was less than stellar before SP1. Uwe -- Novell Support Connection Volunteer SysOp Please don...

Urgent: AutoCompleteExtender doesn't work/Updatepanel doesn't work
This is my code for the AutoCompleteExtender <asp:textbox id="txtQuickSearch" runat="server" CssClass="inputText" style="width:145px; "></asp:textbox> <atlas:AutoCompleteExtender runat="server" ID="acSearch"> <atlas:AutoCompleteProperties TargetControlID="txtQuickSearch" Enabled="True" ServicePath="http://localhost/Sony.BusinessSuite.Web.UI/AtlasServices/MasterData.asmx" ServiceMethod="GetAllModels" minimumprefixlength="2" /> </atlas:AutoCompleteExtender> When i start typing fiddler shows: # Result Host URL Body Caching Content-Type User-...

Freenx doesn't work, NX doesn't work with compiz. Questions
FreeNX just doesn't work. NX from nomachine installed well, but I guess that limits me to two logins? NX doesn't work with compiz, tho, at least from machines not running compiz. So no great surprise. :-) Is there any way to run startkde that disables compiz and uses kwin? Alternatively, hows the easiest way to handle alternative logins? I could link the two documents folders together, but then I'd have problems with file permissions. I'm just looking for ideas here, I could live with two logins. -- dougnc -------------------------------------------...

Can't get the Web Controls to work.. The Build.Bat file doesn't work? HELP>> ARGGG>.
Hi.. I was wanting to use the IE Web Controls, the Tab Strip, etc, and play with it.. Since I have IIS 5, I thought I'd copy them there using the Read me.txt instructions and then copy to a dev server that I use at a web host.. Well, everything worked except the Build file doesn't build the Microsoft.UI.Webcontrols.DLL file? When I try to run it by double clicking on it, it runs really fast in  the DOS window, but I can't see what it says and it closes.. So I tried to do so manually and I received an error that the "cse.exe is not recognized as an internal or external command or batch...

can't get serverside dw functions to work: "Object doesn't support this property or method"
This is a multi-part message in MIME format. ------=_NextPart_000_00D7_01BF98D3.2B917E60 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: quoted-printable When the user hits update, I want to display a blank row. To do that I = have this code in my page: if (dwMine_action + "" !=3D "undefined")=20 {=20 retVal =3D dwMine.SetAction (dwMine_action, dwMine_context);=20 Response.Write(dwMine_action); // for testing=20 if (dwMine_action =3D=3D "Update") {dwMine.InsertRow(0);}=20 } Response.Write( d...

Post Back doesn't work for post method
I have just installed IIS and ASP.NET running on my XP professional machine. I am just checking to see if the setup is working and the page sort of works, but not on the submit (post back). When the page first displays it displays the push button correctly and everything else is blank. Here is my code: CODE <script runat="server"> Sub Page_Load if Page.IsPostBack then lbl1.Text="The date and time is " & now() end if End Sub Sub submit(s As Object, e As EventArgs) lbl2.Text="Hello World!" End Sub </scri...

"Find All References" returns zero results on classes/methods etc. Refactor doesn't work. VS 2005 worked fine, 2008 does not..any ideas?
Hi all, We have a fairly large solution that started in VS 2005, we never had one issue with 2005 pro, or 2005 pro SP1. We recently installed VS 2008 professional with SP1 and ran our solution through the upgrade wizard with zero errors. We currently cannot use the "find all references" feature, refactor doesn't work either (obviously). It returns no symbol results when we attempt to find all references of a method, class, etc. We've searched long and hard through google and forums to find an answer, but have yet to fix the issue. VS doesn't crash, it just returns no re...

keeps making me download update, but, update doesn't work, makes me download update, update doesn't work..................
Name: donald davis Email: galenachefatyahoodotcom Product: Firefox Summary: keeps making me download update, but, update doesn't work, makes me download update, update doesn't work.................. Comments: That's pretty much the whole deal. An update screen pops up, I update, the update doesn't take and the next time I use firefox mozilla the same thing happens over and over and over. Thanks Browser Details: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.4 ...

I can't seem to get a skin to work in 3.0.13 that worked fine in 2.1.2. I know I'm doing *something* wrong, but after two weeks of trying, I'm stumped...
Yiikes.  Back again.  I am having the strangest things happen with my skins now.  Images specified in a css file no longer show up.  When I enter a specific path into my ascx file (assuming the skin folder as the root directory), and upload the skin, to me, it appears to not be parsing at all.  When I 'Apply' the skin, any of my skins, I get nothing.  If I add the above image file to the ascx file, upload, parse and apply, I get an 'x' bad image, and when I click properties, the location of the image file is stating it is in the dotnetnuke/ rooot folder....

Installation 'Sybase DataWindow PS' printer on W98 doesn't work (so PDF export can't work either)
I have a problem with export DataWindow content to PDF on W98 systems. (I don't have any problem with PDF export on other systems like as WINNT, W2K, WXP). I found out that the problem is in the Sybase DataWindow PS printer. It looks like installed but it DOESN'T WORK on W98. When I try print something on this printer then no PostScript file is created. So I tried manual installation of it but it occurs an error during manual installation (I used description of instalation from Bruce Armstrong). The error said that printer driver (PSCRIPT.DLL) can't be loaded. I use...

Getting the values form the previous form and re-use in saving connection doesn't work...
Hello,I have a web form and each web form is saving to a specific user folder.  When the user login with their username and password and go to the web form, fill-out all the information and save to the user folder database, the saving data to the database is working, but now I want to change the directory of the saving data to a specific user folder control db that based on the username, but seems like didn't get to the right user valid path, So instead of this directory 'C:\WINNT\profiles\controls\test.mdb' , I want to save it in a user folder database with their username l...

Same app in two application directories
Hi All, I'm developing an ASP.net app on my local machine.  I have had Visual Studio create an application directory under "Default Web Site", and I have also created an application directory myself via inetmgr (IIS7 on Vista).  The directory created by VS works perfectly, but the directory which I created manually doesn't - every page I load returns a "could not load type" error.  The exact same files exist in both directories (I literally copied them from my dev directory to the one I created), so I know it's not the source files themselves.&...

Forms Authentication doesn't work on remote server but works locally.. why?
I can't seem to figure this out. The same code base works on my localhost but not on the remote server. Forms Authentication keeps timing out remotely. Here's my web.config for the virtual root. <authentication mode="Forms"> <forms loginUrl="ui/Consumer/Registration/Registration.aspx" name=".dailyspecials_cookie" path="/" timeout="700000" protection="All"> </forms> </authentication> and if my "secret" directory, my web.config looks like this...

Web resources about - Form-Methode Get works fine but Post doesn't work - asp.net.mvc

Resources last updated: 12/16/2015 9:45:48 AM