Search Results

Search found 64 results on 3 pages for 'rememberme'.

Page 1/3 | 1 2 3  | Next Page >

  • Spring Security RememberMe Services with Session Cookie

    - by Jarrod
    I am using Spring Security's RememberMe Services to keep a user authenticated. I would like to find a simple way to have the RememberMe cookie set as a session cookie rather than with a fixed expiration time. For my application, the cookie should persist until the user closes the browser. Any suggestions on how to best implement this? Any concerns on this being a potential security problem? The primary reason for doing so is that with a cookie-based token, any of the servers behind our load balancer can service a protected request without relying on the user's Authentication to be stored in an HttpSession. In fact, I have explicitly told Spring Security to never create sessions using the namespace. Further, we are using Amazon's Elastic Load Balancing, and so sticky sessions are not supported. NB: Although I am aware that as of Apr. 08, Amazon now supports sticky sessions, I still do not want to use them for a handful of other reasons. Namely that the untimely demise of one server would still cause the loss of sessions for all users associated with it. http://aws.amazon.com/about-aws/whats-new/2010/04/08/support-for-session-stickiness-in-elastic-load-balancing/

    Read the article

  • ASP.NET MVC localization DisplayNameAttribute alternatives: a good way

    - by Brian Schroer
    The ASP.NET MVC HTML helper methods like .LabelFor and .EditorFor use model metadata to autogenerate labels for model properties. By default it uses the property name for the label text, but if that’s not appropriate, you can use a DisplayName attribute to specify the desired label text: [DisplayName("Remember me?")] public bool RememberMe { get; set; } I’m working on a multi-language web site, so the labels need to be localized. I tried pointing the DisplayName attribute to a resource string: [DisplayName(MyResource.RememberMe)] public bool RememberMe { get; set; } …but that results in the compiler error "An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type”. I got around this by creating a custom LocalizedDisplayNameAttribute class that inherits from DisplayNameAttribute: 1: public class LocalizedDisplayNameAttribute : DisplayNameAttribute 2: { 3: public LocalizedDisplayNameAttribute(string resourceKey) 4: { 5: ResourceKey = resourceKey; 6: } 7:   8: public override string DisplayName 9: { 10: get 11: { 12: string displayName = MyResource.ResourceManager.GetString(ResourceKey); 13:   14: return string.IsNullOrEmpty(displayName) 15: ? string.Format("[[{0}]]", ResourceKey) 16: : displayName; 17: } 18: } 19:   20: private string ResourceKey { get; set; } 21: } Instead of a display string, it takes a constructor argument of a resource key. The DisplayName method is overridden to get the display string from the resource file (line 12). If the key is not found, I return a formatted string containing the key (e.g. “[[RememberMe]]”) so I can tell by looking at my web pages which resource keys I haven’t defined yet (line 15). The usage of my custom attribute in the model looks like this: [LocalizedDisplayName("RememberMe")] public bool RememberMe { get; set; } That was my first attempt at localized display names, and it’s a technique that I still use in some cases, but in my next post I’ll talk about the method that I now prefer, a custom DataAnnotationsModelMetadataProvider class…

    Read the article

  • ASP.NET MVC RememberMe(It's large, please don't quit reading. Have explained the problem in detail a

    - by nccsbim071
    After searching a lot i did not get any answers and finally i had to get back to you. Below i am explaining my problem in detail. It's too long, so please don't quit reading. I have explained my problem in simple language. I have been developing an asp.net mvc project. I am using standard ASP.NET roles and membership. Everything is working fine but the remember me functionality doesn't work at all. I am listing all the details of work. Hope you guys can help me out solve this problem. I simply need this: I need user to login to web application. During login they can either login with remember me or without it. If user logs in with remember me, i want browser to remember them for long time, let's say atleast one year or considerably long time. The way they do it in www.dotnetspider.com,www.codeproject.com,www.daniweb.com and many other sites. If user logs in without remember me, then browser should allow access to website for some 20 -30 minutes and after that their session should expire. Their session should also expire when user logs in and shuts down the browser without logging out. Note: I have succesfully implemented above functionality without using standard asp.net roles and membership by creating my own talbes for user and authenticating against my database table, setting cookie and sessions in my other projects. But for this project we starting from the beginning used standard asp.net roles and membership. We thought it will work and after everything was build at the time of testing it just didn't work. and now we cannot replace the existing functionality with standard asp.net roles and membership with my own custom user tables and all the stuff, you understand what i am taling about. Either there is some kind of bug with standard asp.net roles and membership functionality or i have the whole concept of standard asp.net roles and membership wrong. i have stated what i want above. I think it's very simple and reasonable. What i did Login form with username,password and remember me field. My setting in web.config: <authentication mode="Forms"> <forms loginUrl="~/Account/LogOn" timeout="2880"/> </authentication> in My controller action, i have this: FormsAuth.SignIn(userName, rememberMe); public void SignIn(string userName, bool createPersistentCookie) { FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); } Now the problems are following: I have already stated in above section "I simply need this". user can successfully log in to the system. Their session exists for as much minutes as specified in timeout value in web.config. I have also given a sample of my web.config. In my samplem if i set the timeout to 5 minutes,then user session expires after 5 minutes, that's ok. But if user closes the browser and reopen the browser, user can still enter the website without loggin in untill time specified in "timeout" has not passed out. The sliding expiration for timeout value is also working fine. Now if user logs in to the system with remember me checked, user session still expires after 5 minutes. This is not good behaviour, is it?. I mean to say that if user logs in to the system with remember me checked he should be remembered for a long time untill he doesn't logs out of the system or user doesn't manually deletes all the cookies from the browser. If user logs in to the system without remember me checked his session should expire after the timeout period values specified in web.config and also if users closes the browser. The problem is that if user closes the browser and reopens it he can still enter the website without logging in. I search internet a lot on this topic, but i could not get the solution. In the blog post(http://weblogs.asp.net/scottgu/archive/2005/11/08/430011.aspx) made by Scott Gu on exactly the same topic. The users are complaining about the same thing in their comments ut there is no easy solution given in by Mr. Scott. I read it at following places: http://weblogs.asp.net/scottgu/archive/2005/11/08/430011.aspx http://geekswithblogs.net/vivek/archive/2006/09/14/91191.aspx I guess this is a problem of lot's of users. As seem from blog post made by Mr. Scott Gu. Your help will be really appreciated. Thanks in advance.

    Read the article

  • ASP.NET RememberMe(It's large, please don't quit reading. Have explained the problem in detail and s

    - by nccsbim071
    After searching a lot i did not get any answers and finally i had to get back to you. Below i am explaining my problem in detail. It's too long, so please don't quit reading. I have explained my problem in simple language. I have been developing an asp.net mvc project. I am using standard ASP.NET roles and membership. Everything is working fine but the remember me functionality doesn't work at all. I am listing all the details of work. Hope you guys can help me out solve this problem. I simply need this: I need user to login to web application. During login they can either login with remember me or without it. If user logs in with remember me, i want browser to remember them for long time, let's say atleast one year or considerably long time. The way they do it in www.dotnetspider.com,www.codeproject.com,www.daniweb.com and many other sites. If user logs in without remember me, then browser should allow access to website for some 20 -30 minutes and after that their session should expire. Their session should also expire when user logs in and shuts down the browser without logging out. Note: I have succesfully implemented above functionality without using standard asp.net roles and membership by creating my own talbes for user and authenticating against my database table, setting cookie and sessions in my other projects. But for this project we starting from the beginning used standard asp.net roles and membership. We thought it will work and after everything was build at the time of testing it just didn't work. and now we cannot replace the existing functionality with standard asp.net roles and membership with my own custom user tables and all the stuff, you understand what i am taling about. Either there is some kind of bug with standard asp.net roles and membership functionality or i have the whole concept of standard asp.net roles and membership wrong. i have stated what i want above. I think it's very simple and reasonable. What i did Login form with username,password and remember me field. My setting in web.config: in My controller action, i have this: FormsAuth.SignIn(userName, rememberMe); public void SignIn(string userName, bool createPersistentCookie) { FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); } Now the problems are following: I have already stated in above section "I simply need this". user can successfully log in to the system. Their session exists for as much minutes as specified in timeout value in web.config. I have also given a sample of my web.config. In my samplem if i set the timeout to 5 minutes,then user session expires after 5 minutes, that's ok. But if user closes the browser and reopen the browser, user can still enter the website without loggin in untill time specified in "timeout" has not passed out. The sliding expiration for timeout value is also working fine. Now if user logs in to the system with remember me checked, user session still expires after 5 minutes. This is not good behaviour, is it?. I mean to say that if user logs in to the system with remember me checked he should be remembered for a long time untill he doesn't logs out of the system or user doesn't manually deletes all the cookies from the browser. If user logs in to the system without remember me checked his session should expire after the timeout period values specified in web.config and also if users closes the browser. The problem is that if user closes the browser and reopens it he can still enter the website without logging in. I search internet a lot on this topic, but i could not get the solution. In the blog post(http://weblogs.asp.net/scottgu/archive/2005/11/08/430011.aspx) made by Scott Gu on exactly the same topic. The users are complaining about the same thing in their comments ut there is no easy solution given in by Mr. Scott. I read it at following places: http://weblogs.asp.net/scottgu/archive/2005/11/08/430011.aspx http://geekswithblogs.net/vivek/archive/2006/09/14/91191.aspx I guess this is a problem of lot's of users. As seem from blog post made by Mr. Scott Gu. Your help will be really appreciated. Thanks in advance.

    Read the article

  • Returning Json object from controller action to jQuery

    - by PsychoCoder
    I'm attempting to get this working properly (2 days now). I'm working on a log in where I'm calling the controller action from jQuery, passing it a JSON object (utilizing json2.js) and returning a Json object from the controller. I'm able to call the action fine, but instead of being able to put the response where I want it it just opens a new window with this printed on the screen: {"Message":"Invalid username/password combination"} And the URL looks like http://localhost:13719/Account/LogOn so instead of calling the action and not reloading the page it's taking the user to the controller, which isn't good. So now for some code, first the controller code [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl = "") { if (ModelState.IsValid) { var login = ObjectFactory.GetInstance<IRepository<PhotographerLogin>>(); var user = login.FindOne(x => x.Login == model.Username && x.Pwd == model.Password); if (user == null) return Json(new FailedLoginViewModel { Message = "Invalid username/password combination" }); else { if (!string.IsNullOrEmpty(returnUrl)) return Redirect(returnUrl); else return RedirectToAction("Index", "Home"); } } return RedirectToAction("Index", "Home"); } And the jQuery code $("#signin_submit").click(function () { var login = getLogin(); $.ajax({ type: "POST", url: "../Account/LogOn", data: JSON.stringify(login), dataType: 'json', contentType: 'application/json; charset=utf-8', error: function (xhr) { $("#message").text(xhr.statusText); }, success: function (result) { } }); }); function getLogin() { var un = $("#username").val(); var pwd = $("#password").val(); var rememberMe = $("#rememberme").val(); return (un == "") ? null : { Username: un, Password: pwd, RememberMe: rememberMe }; } In case you need to see the actual login form here that is as well <fieldset id="signin_menu"> <div> <span id="message"></span> </div> <% Html.EnableClientValidation(); %> <% using (Html.BeginForm("LogOn", "Account", FormMethod.Post, new { @id = "signin" })) {%> <% ViewContext.FormContext.ValidationSummaryId = "valLogOnContainer"; %> <%= Html.LabelFor(m => m.Username) %> <%= Html.TextBoxFor(m => m.Username, new { @class = "inputbox", @tabindex = "4", @id = "username" })%><%= Html.ValidationMessageFor(m => m.Username, "*")%> <p> <%= Html.LabelFor(m=>m.Password) %> <%= Html.PasswordFor(m => m.Password, new { @class = "inputbox", @tabindex = "5", @id = "password" })%><%= Html.ValidationMessageFor(m => m.Password, "*")%> </p> <p class="remember"> <input id="signin_submit" value="Sign in" tabindex="6" type="submit"/> <%= Html.CheckBoxFor(m => m.RememberMe, new { @class = "inputbox", @tabindex = "7", @id = "rememberme" })%> <%= Html.LabelFor(m => m.RememberMe) %> <p class="forgot"> <a href="#" id="forgot_password_link" title="Click here to reset your password.">Forgot your password?</a> </p> <p class="forgot-username"> <a href="#" id="forgot_username_link" title="Fogot your login name? We can help with that">Forgot your username?</a> </p> </p> <%= Html.ValidationSummaryJQuery("Please fix the following errors.", new Dictionary<string, object> { { "id", "valLogOnContainer" } })%> <% } %> </fieldset> The login form is loaded on the main page with <% Html.RenderPartial("LogonControl");%> Not sure if that has any bearing on this or not but thought I'd mention it. EDIT: The login form is loaded similar to the Twitter login, click a link and the form loads with the help of jQuery & CSS

    Read the article

  • Android: HttpURLConnection not working properly

    - by giorgiline
    I'm trying to get the cookies from a website after sending user credentials through a POST Request an it seems that it doesn't work in android this way. ¿Am I doing something bad?. Please help. I've searched here in different posts but there's no useful answer. It's curious that this run in a desktop Java implementation it works perfect but it crashes in Android platform. And it is exactly the same code, specifically when calling HttpURLConnection.getHeaderFields(), it also happens with other member methods. It's a simple code and I don't know why the hell isn't working. DESKTOP CODE: This goes just in the main() HttpURLConnection connection = null; OutputStream out = null; try { URL url = new URL("http://www.XXXXXXXX.php"); String charset = "UTF-8"; String postback = "1"; String user = "XXXXXXXXX"; String password = "XXXXXXXX"; String rememberme = "on"; String query = String.format("postback=%s&user=%s&password=%s&rememberme=%s" , URLEncoder.encode(postback, charset) , URLEncoder.encode(user,charset) , URLEncoder.encode(password, charset) , URLEncoder.encode(rememberme, charset)); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept-Charset", charset); connection.setDoOutput(true); connection.setFixedLengthStreamingMode(query.length()); out = connection.getOutputStream (); out.write(query.getBytes(charset)); if (connection.getHeaderFields() == null){ System.out.println("Header null"); }else{ for (String cookie: connection.getHeaderFields().get("Set-Cookie")){ System.out.println(cookie.split(";", 2)[0]); } } } catch (IOException e){ e.printStackTrace(); } finally { try { out.close();} catch (IOException e) { e.printStackTrace();} connection.disconnect(); } So the output is: login_key=20ad8177db4eca3f057c14a64bafc2c9 FASID=cabf20cc471fcacacdc7dc7e83768880 track=30c8183e4ebbe8b3a57b583166326c77 client-data=%7B%22ism%22%3Afalse%2C%22showm%22%3Afalse%2C%22ts%22%3A1349189669%7D ANDROID CODE: This goes inside doInBackground AsyncTask body HttpURLConnection connection = null; OutputStream out = null; try { URL url = new URL("http://www.XXXXXXXXXXXXXX.php"); String charset = "UTF-8"; String postback = "1"; String user = "XXXXXXXXX"; String password = "XXXXXXXX"; String rememberme = "on"; String query = String.format("postback=%s&user=%s&password=%s&rememberme=%s" , URLEncoder.encode(postback, charset) , URLEncoder.encode(user,charset) , URLEncoder.encode(password, charset) , URLEncoder.encode(rememberme, charset)); connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Accept-Charset", charset); connection.setDoOutput(true); connection.setFixedLengthStreamingMode(query.length()); out = connection.getOutputStream (); out.write(query.getBytes(charset)); if (connection.getHeaderFields() == null){ Log.v(TAG, "Header null"); }else{ for (String cookie: connection.getHeaderFields().get("Set-Cookie")){ Log.v(TAG, cookie.split(";", 2)[0]); } } } catch (IOException e){ e.printStackTrace(); } finally { try { out.close();} catch (IOException e) { e.printStackTrace();} connection.disconnect(); } And here there is no output, it seems that connection.getHeaderFields() doesn't return result. It takes al least 30 seconds to show the Log: 10-02 16:56:25.918: V/class com.giorgi.myproject.activities.HomeActivity(2596): Header null

    Read the article

  • Spring Security - Interactive login attempt was unsuccessful

    - by Taylor L
    I've been trying to track down why Spring Security isn't creating the SPRING_SECURITY_REMEMBER_ME_COOKIE so I turned on logging for org.springframework.security.web.authentication.rememberme. At first glance, the logs make it seem like the login is failing but the login is actually successful in the sense that if I navigate to a page that requires authentication I am not redirected back to the login page. However, the logs appear to be saying the login credentials are invalid. Any ideas as to what is going on? Mar 16, 2010 10:05:56 AM org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices onLoginSuccess FINE: Creating new persistent login for user [email protected] Mar 16, 2010 10:10:07 AM org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices loginFail FINE: Interactive login attempt was unsuccessful. Mar 16, 2010 10:10:07 AM org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices cancelCookie FINE: Cancelling cookie <http auto-config="false"> <intercept-url pattern="/css/**" filters="none" /> <intercept-url pattern="/img/**" filters="none" /> <intercept-url pattern="/js/**" filters="none" /> <intercept-url pattern="/app/admin/**" filters="none" /> <intercept-url pattern="/app/login/**" filters="none" /> <intercept-url pattern="/app/register/**" filters="none" /> <intercept-url pattern="/app/error/**" filters="none" /> <intercept-url pattern="/" filters="none" /> <intercept-url pattern="/**" access="ROLE_USER" /> <logout logout-success-url="/" /> <form-login login-page="/app/login" default-target-url="/" authentication-failure-url="/app/login?login_error=1" /> <session-management invalid-session-url="/app/login" /> <remember-me services-ref="rememberMeServices" key="myKey" /> </http> <authentication-manager alias="authenticationManager"> <authentication-provider user-service-ref="userDetailsService"> <password-encoder hash="sha-256" base64="true"> <salt-source user-property="username" /> </password-encoder> </authentication-provider> </authentication-manager> <beans:bean id="userDetailsService" class="com.my.service.auth.UserDetailsServiceImpl" /> <beans:bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices"> <beans:property name="userDetailsService" ref="userDetailsService" /> <beans:property name="tokenRepository" ref="persistentTokenRepository" /> <beans:property name="key" value="myKey" /> </beans:bean> <beans:bean id="persistentTokenRepository" class="com.my.service.auth.PersistentTokenRepositoryImpl" />

    Read the article

  • How can I use a custom configured RememberMeAuthenticationFilter in spring security?

    - by Sebastian
    I want to use a slightly customized rememberme functionality with spring security (3.1.0). I declare the rememberme tag like this: <security:remember-me key="JNJRMBM" user-service-ref="gymUserDetailService" /> As I have my own rememberme service I need to inject that into the RememberMeAuthenticationFilter which I define like this: <bean id="rememberMeFilter" class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter"> <property name="rememberMeServices" ref="gymRememberMeService"/> <property name="authenticationManager" ref="authenticationManager" /> </bean> I have spring security integrated in a standard way in my web.xml: <filter-name>springSecurityFilterChain</filter-name> <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> Everything works fine, except that the RememberMeAuthenticationFilter uses the standard RememberMeService, so I think that my defined RememberMeAuthenticationFilter is not being used. How can I make sure that my definition of the filter is being used? Do I need to create a custom filterchain? And if so, how can I see my current "implicit" filterchain and make sure I use the same one except my RememberMeAuthenticationFilter instead of the default one? Thanks for any advice and/or pointers!

    Read the article

  • All is working except if($_POST['submit']=='Update')

    - by user1319909
    I have a working registration and login system. I am trying to create a form where a user can add product registration info (via mysql update). I can't seem to get the db to actually update the fields. What am I missing here?!? <?php define('INCLUDE_CHECK',true); require 'connect.php'; require 'functions.php'; // Those two files can be included only if INCLUDE_CHECK is defined session_name('tzLogin'); // Starting the session session_set_cookie_params(2*7*24*60*60); // Making the cookie live for 2 weeks session_start(); if($_SESSION['id'] && !isset($_COOKIE['tzRemember']) && !$_SESSION['rememberMe']) { // If you are logged in, but you don't have the tzRemember cookie (browser restart) // and you have not checked the rememberMe checkbox: $_SESSION = array(); session_destroy(); // Destroy the session } if(isset($_GET['logoff'])) { $_SESSION = array(); session_destroy(); header("Location: index_login3.php"); exit; } if($_POST['submit']=='Login') { // Checking whether the Login form has been submitted $err = array(); // Will hold our errors if(!$_POST['username'] || !$_POST['password']) $err[] = 'All the fields must be filled in!'; if(!count($err)) { $_POST['username'] = mysql_real_escape_string($_POST['username']); $_POST['password'] = mysql_real_escape_string($_POST['password']); $_POST['rememberMe'] = (int)$_POST['rememberMe']; // Escaping all input data $row = mysql_fetch_assoc(mysql_query("SELECT * FROM electrix_users WHERE usr='{$_POST['username']}' AND pass='".md5($_POST['password'])."'")); if($row['usr']) { // If everything is OK login $_SESSION['usr']=$row['usr']; $_SESSION['id'] = $row['id']; $_SESSION['email'] = $row['email']; $_SESSION['first'] = $row['first']; $_SESSION['last'] = $row['last']; $_SESSION['address1'] = $row['address1']; $_SESSION['address2'] = $row['address2']; $_SESSION['city'] = $row['city']; $_SESSION['state'] = $row['state']; $_SESSION['zip'] = $row['zip']; $_SESSION['country'] = $row['country']; $_SESSION['product1'] = $row['product1']; $_SESSION['serial1'] = $row['serial1']; $_SESSION['product2'] = $row['product2']; $_SESSION['serial2'] = $row['serial2']; $_SESSION['product3'] = $row['product3']; $_SESSION['serial3'] = $row['serial3']; $_SESSION['rememberMe'] = $_POST['rememberMe']; // Store some data in the session setcookie('tzRemember',$_POST['rememberMe']); } else $err[]='Wrong username and/or password!'; } if($err) $_SESSION['msg']['login-err'] = implode('<br />',$err); // Save the error messages in the session header("Location: index_login3.php"); exit; } else if($_POST['submit']=='Register') { // If the Register form has been submitted $err = array(); if(strlen($_POST['username'])<4 || strlen($_POST['username'])>32) { $err[]='Your username must be between 3 and 32 characters!'; } if(preg_match('/[^a-z0-9\-\_\.]+/i',$_POST['username'])) { $err[]='Your username contains invalid characters!'; } if(!checkEmail($_POST['email'])) { $err[]='Your email is not valid!'; } if(!count($err)) { // If there are no errors $pass = substr(md5($_SERVER['REMOTE_ADDR'].microtime().rand(1,100000)),0,6); // Generate a random password $_POST['email'] = mysql_real_escape_string($_POST['email']); $_POST['username'] = mysql_real_escape_string($_POST['username']); $_POST['first'] = mysql_real_escape_string($_POST['first']); $_POST['last'] = mysql_real_escape_string($_POST['last']); $_POST['address1'] = mysql_real_escape_string($_POST['address1']); $_POST['address2'] = mysql_real_escape_string($_POST['address2']); $_POST['city'] = mysql_real_escape_string($_POST['city']); $_POST['state'] = mysql_real_escape_string($_POST['state']); $_POST['zip'] = mysql_real_escape_string($_POST['zip']); $_POST['country'] = mysql_real_escape_string($_POST['country']); // Escape the input data mysql_query(" INSERT INTO electrix_users(usr,pass,email,first,last,address1,address2,city,state,zip,country,regIP,dt) VALUES( '".$_POST['username']."', '".md5($pass)."', '".$_POST['email']."', '".$_POST['first']."', '".$_POST['last']."', '".$_POST['address1']."', '".$_POST['address2']."', '".$_POST['city']."', '".$_POST['state']."', '".$_POST['zip']."', '".$_POST['country']."', '".$_SERVER['REMOTE_ADDR']."', NOW() )"); if(mysql_affected_rows($link)==1) { send_mail( '[email protected]', $_POST['email'], 'Your New Electrix User Password', 'Thank you for registering at www.electrixpro.com. Your password is: '.$pass); $_SESSION['msg']['reg-success']='We sent you an email with your new password!'; } else $err[]='This username is already taken!'; } if(count($err)) { $_SESSION['msg']['reg-err'] = implode('<br />',$err); } header("Location: index_login3.php"); exit; } if($_POST['submit']=='Update') { { mysql_query(" UPDATE electrix_users(product1,serial1,product2,serial2,product3,serial3) WHERE usr='{$_POST['username']}' VALUES( '".$_POST['product1']."', '".$_POST['serial1']."', '".$_POST['product2']."', '".$_POST['serial2']."', '".$_POST['product3']."', '".$_POST['serial3']."', )"); if(mysql_affected_rows($link)==1) { $_SESSION['msg']['upd-success']='Thank you for registering your Electrix product'; } else $err[]='So Sad!'; } if(count($err)) { $_SESSION['msg']['upd-err'] = implode('<br />',$err); } header("Location: index_login3.php"); exit; } if($_SESSION['msg']) { // The script below shows the sliding panel on page load $script = ' <script type="text/javascript"> $(function(){ $("div#panel").show(); $("#toggle a").toggle(); }); </script>'; } ?>

    Read the article

  • ASP.NET MVC localization DisplayNameAttribute alternatives: a better way

    - by Brian Schroer
    In my last post, I talked bout creating a custom class inheriting from System.ComponentModel.DisplayNameAttribute to retrieve display names from resource files: [LocalizedDisplayName("RememberMe")] public bool RememberMe { get; set; } That’s a lot of work to put an attribute on all of my model properties though. It would be nice if I could intercept the ASP.NET MVC code that analyzes the model metadata to retrieve display names to make it automatically get localized text from my resource files. That way, I could just set up resource file entries where the keys are the property names, and not have to put attributes on all of my properties. That’s done by creating a custom class inheriting from System.Web.Mvc.DataAnnotationsModelMetadataProvider: 1: public class LocalizedDataAnnotationsModelMetadataProvider : 2: DataAnnotationsModelMetadataProvider 3: { 4: protected override ModelMetadata CreateMetadata( 5: IEnumerable<Attribute> attributes, 6: Type containerType, 7: Func<object> modelAccessor, 8: Type modelType, 9: string propertyName) 10: { 11: var meta = base.CreateMetadata 12: (attributes, containerType, modelAccessor, modelType, propertyName); 13:   14: if (string.IsNullOrEmpty(propertyName)) 15: return meta; 16:   17: if (meta.DisplayName == null) 18: GetLocalizedDisplayName(meta, propertyName); 19:   20: if (string.IsNullOrEmpty(meta.DisplayName)) 21: meta.DisplayName = string.Format("[[{0}]]", propertyName); 22:   23: return meta; 24: } 25:   26: private static void GetLocalizedDisplayName(ModelMetadata meta, string propertyName) 27: { 28: ResourceManager resourceManager = MyResource.ResourceManager; 29: CultureInfo culture = Thread.CurrentThread.CurrentUICulture; 30:   31: meta.DisplayName = resourceManager.GetString(propertyName, culture); 32: } 33: } Line 11 calls the base CreateMetadata method. Line 17 checks whether the metadata DisplayName property has already been populated by a DisplayNameAttribute (or my LocalizedDisplayNameAttribute). If so, it respects that and doesn’t use my custom localized text lookup. The GetLocalizedDisplayName method checks for the property name as a resource file key. If found, it uses the localized text from the resource files. If the key is not found in the resource file, as with my LocalizedDisplayNameAttribute, I return a formatted string containing the property name (e.g. “[[RememberMe]]”) so I can tell by looking at my web pages which resource keys I haven’t defined yet. It’s hooked up with this code in the Application_Start method of Global.asax: ModelMetadataProviders.Current = new LocalizedDataAnnotationsModelMetadataProvider();

    Read the article

  • Spring Security - Persistent Remember Me Issue

    - by Taylor L
    I've been trying to track down why Spring Security isn't creating the Spring Security remember me cookie (SPRING_SECURITY_REMEMBER_ME_COOKIE). At first glance, the logs make it seem like the login is failing, but the login is actually successful in the sense that if I navigate to a page that requires authentication I am not redirected back to the login page. However, the logs appear to be saying the login credentials are invalid. I'm using Spring 3.0.1, Spring Security 3.0.1, and Google App Engine 1.3.1. Any ideas as to what is going on? Mar 16, 2010 10:05:56 AM org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices onLoginSuccess FINE: Creating new persistent login for user [email protected] Mar 16, 2010 10:10:07 AM org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices loginFail FINE: Interactive login attempt was unsuccessful. Mar 16, 2010 10:10:07 AM org.springframework.security.web.authentication.rememberme.AbstractRememberMeServices cancelCookie FINE: Cancelling cookie Below is the relevant portion of the applicationContext-security.xml. <http auto-config="false"> <intercept-url pattern="/css/**" filters="none" /> <intercept-url pattern="/img/**" filters="none" /> <intercept-url pattern="/js/**" filters="none" /> <intercept-url pattern="/app/admin/**" filters="none" /> <intercept-url pattern="/app/login/**" filters="none" /> <intercept-url pattern="/app/register/**" filters="none" /> <intercept-url pattern="/app/error/**" filters="none" /> <intercept-url pattern="/" filters="none" /> <intercept-url pattern="/**" access="ROLE_USER" /> <logout logout-success-url="/" /> <form-login login-page="/app/login" default-target-url="/" authentication-failure-url="/app/login?login_error=1" /> <session-management invalid-session-url="/app/login" /> <remember-me services-ref="rememberMeServices" key="myKey" /> </http> <authentication-manager alias="authenticationManager"> <authentication-provider user-service-ref="userDetailsService"> <password-encoder hash="sha-256" base64="true"> <salt-source user-property="username" /> </password-encoder> </authentication-provider> </authentication-manager> <beans:bean id="userDetailsService" class="com.my.service.auth.UserDetailsServiceImpl" /> <beans:bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.PersistentTokenBasedRememberMeServices"> <beans:property name="userDetailsService" ref="userDetailsService" /> <beans:property name="tokenRepository" ref="persistentTokenRepository" /> <beans:property name="key" value="myKey" /> </beans:bean> <beans:bean id="persistentTokenRepository" class="com.my.service.auth.PersistentTokenRepositoryImpl" />

    Read the article

  • How to explicitly add a cookie in Watir?

    - by Sands
    I need to set a cookie in IE to execute some specific flow. I tried using the following code ieb = Watir::IE.new ieb.document.cookie="rememberme=foobar;Path=/; Domain=sometestdomain.com" # Bring up browser and do bunch of stuff However, I see that when the IE comes up, rememberme cookie is not set. Am I doing something wrong here?

    Read the article

  • Getting a 'base' Domain from a Domain

    - by Rick Strahl
    Here's a simple one: How do you reliably get the base domain from full domain name or URI? Specifically I've run into this scenario in a few recent applications when creating the Forms Auth Cookie in my ASP.NET applications where I explicitly need to force the domain name to the common base domain. So, www.west-wind.com, store.west-wind.com, west-wind.com, dev.west-wind.com all should return west-wind.com. Here's the code where I need to use this type of logic for issuing an AuthTicket explicitly:private void IssueAuthTicket(UserState userState, bool rememberMe) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userState.UserId, DateTime.Now, DateTime.Now.AddDays(10), rememberMe, userState.ToString()); string ticketString = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketString); cookie.HttpOnly = true; if (rememberMe) cookie.Expires = DateTime.Now.AddDays(10); // write out a domain cookie cookie.Domain = Request.Url.GetBaseDomain(); HttpContext.Response.Cookies.Add(cookie); } Now unfortunately there's no Uri.GetBaseDomain() method unfortunately, as I was surprised to find out. So I ended up creating one:public static class NetworkUtils { /// <summary> /// Retrieves a base domain name from a full domain name. /// For example: www.west-wind.com produces west-wind.com /// </summary> /// <param name="domainName">Dns Domain name as a string</param> /// <returns></returns> public static string GetBaseDomain(string domainName) { var tokens = domainName.Split('.'); // only split 3 segments like www.west-wind.com if (tokens == null || tokens.Length != 3) return domainName; var tok = new List<string>(tokens); var remove = tokens.Length - 2; tok.RemoveRange(0, remove); return tok[0] + "." + tok[1]; ; } /// <summary> /// Returns the base domain from a domain name /// Example: http://www.west-wind.com returns west-wind.com /// </summary> /// <param name="uri"></param> /// <returns></returns> public static string GetBaseDomain(this Uri uri) { if (uri.HostNameType == UriHostNameType.Dns) return GetBaseDomain(uri.DnsSafeHost); return uri.Host; } } I've had a need for this so frequently it warranted a couple of helpers. The second Uri helper is an Extension method to the Uri class, which is what's used the in the first code sample. This is the preferred way to call this since the URI class can differentiate between Dns names and IP Addresses. If you use the first string based version there's a little more guessing going on if a URL is an IP Address. There are a couple of small twists in dealing with 'domain names'. When passing a string only there's a possibility to not actually pass domain name, but end up passing an IP address, so the code explicitly checks for three domain segments (can there be more than 3?). IP4 Addresses have 4 and IP6 have none so they'll fall through. Then there are things like localhost or a NetBios machine name which also come back on URL strings, but also shouldn't be handled. Anyway, small thing but maybe somebody else will find this useful.© Rick Strahl, West Wind Technologies, 2005-2012Posted in ASP.NET  Networking   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Can't log in a user in MVC!

    - by devlife
    I have been scratching my head on this for a while now but still can't get it. I'm trying to simply log in a user in an MVC2 application. I have tried everything that I know to try but still can't figure out what I'm doing wrong. Here are a few things that I have tried: FormsAuthentication.SetAuthCookie( emailAddress, rememberMe ); var cookie = FormsAuthentication.GetAuthCookie( emailAddress, rememberMe ); HttpContext.Response.Cookies.Add( cookie ); FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( emailAddress, rememberMe, 15 ); FormsIdentity identity = new FormsIdentity( ticket ); GenericPrincipal principal = new GenericPrincipal(identity, new string[0]); HttpContext.User = principal; I'm not sure if any of this is the right thing to do (as it's not working). After setting HttpContext.User = principal then Request.IsAuthenticated == true. However, in Global.asax I have this: HttpCookie authenCookie = Context.Request.Cookies.Get( FormsAuthentication.FormsCookieName ); The only cookie that ever is available is the aspnet session cookie. Any ideas at all would be much appreciated!

    Read the article

  • MVC Scaffold Template Not Generating?

    - by monkey9987
    Been working on an MVC project and my templates were not generating. I first created my Model inside my "Models" folder, then did a quick compile. Next I went to the Views folder to get it created, right click and say "Add View" then I clicked the checkbox to create an edit page. What happened was the template would never seem to pull in my Model, it would just have the default header items, but the entire model was missing.  My model was defined as follows: public class LogOnModel { [Required][Display(Name = "User name")]public string UserName;[Required][DataType(DataType.Password)][Display(Name = "Password")]public string Password;[Display(Name = "Remember me?")]public bool RememberMe; } See anything wrong with that? I couldn't figure out why each time I created my View and selected the option to create the "Edit" scaffold automatically, it would come up blank. Turns out I'm missing my get / set methods on the Model class items. Here's my code with the correct setup: public class LogOnModel { [Required][Display(Name = "User name")]public string UserName { get; set; } [Required][DataType(DataType.Password)][Display(Name = "Password")]public string Password { get; set; }[Display(Name = "Remember me?")]public bool RememberMe { get; set; } }  I hope that helps someone out, it's pretty simple when I look at it now, but that's always the case!  ~ Steve

    Read the article

  • Cannot convert lambda expression to type 'string' because it is not a delegate type

    - by RememberME
    I have the following code written by another developer on 2 pages of my site. This used to work just fine, but now is giving the error "Cannot convert lambda expression to type 'string' because it is not a delegate type" on the Delete line with Ajax.ThemeRollerActionLink. I don't go into this section of the site often, and we recently upgraded from MVC 1.0 to 2.0. I'm guessing that's probably when it stopped working. I've looked up this error and the recommended fix seems to be add using System.Linq However, the page already has <%@ Import Namespace="System.Linq" %> <% Html.Grid(Model).Columns(col => { col.For(c => "<a href='" + Url.Action("Edit", new { userName = c }) + "' class=\"fg-button fg-button-icon-solo ui-state-default ui-corner-all\"><span class=\"ui-icon ui-icon-pencil\"></span></a>").Named("Edit").DoNotEncode(); col.For(c => Ajax.ThemeRollerActionLink("fg-button fg-button-icon-solo ui-state-default ui-corner-all", "ui-icon ui-icon-close", "Delete", new { userName = c }, new AjaxOptions { Confirm = "Delete User?", HttpMethod = "Delete", InsertionMode = InsertionMode.Replace, UpdateTargetId = "gridcontainer", OnSuccess = "successDeleteAssignment", OnFailure = "failureDeleteAssignment" })).Named("Delete").DoNotEncode(); col.For(c => c).Named("User"); }).Attributes(id => "userlist").Render(); %>

    Read the article

  • Escape apostrophe when passing parameter in onclick event

    - by RememberME
    I'm passing the company name to an onclick event. Some company names have apostrophes in them. I added '.Replace("'", "'")' to the company_name field. This allows the onclick event to fire, but the confirm message displays as "Jane's Welding Company". <a href="#" onclick="return Actionclick('<%= Url.Action("Activate", new {id = item.company_id}) %>', '<%= Html.Encode(item.company1.company_name.Replace("'", "&#39;")) %>');" class="fg-button fg-button-icon-solo ui-state-default ui-corner-all"><span class="ui-icon ui-icon-refresh"></span></a> <script type="text/javascript"> function Actionclick(url, companyName) { if (confirm('This action will activate this company\'s primary company ('+companyName+') and all of its other subsidiaries. Continue?')) { location.href = url; }; };

    Read the article

  • Internet Explorer and Cookie Domains

    - by Rick Strahl
    I've been bitten by some nasty issues today in regards to using a domain cookie as part of my FormsAuthentication operations. In the app I'm currently working on we need to have single sign-on that spans multiple sub-domains (www.domain.com, store.domain.com, mail.domain.com etc.). That's what a domain cookie is meant for - when you set the cookie with a Domain value of the base domain the cookie stays valid for all sub-domains. I've been testing the app for quite a while and everything is working great. Finally I get around to checking the app with Internet Explorer and I start discovering some problems - specifically on my local machine using localhost. It appears that Internet Explorer (all versions) doesn't allow you to specify a domain of localhost, a local IP address or machine name. When you do, Internet Explorer simply ignores the cookie. In my last post I talked about some generic code I created to basically parse out the base domain from the current URL so a domain cookie would automatically used using this code:private void IssueAuthTicket(UserState userState, bool rememberMe) { FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, userState.UserId, DateTime.Now, DateTime.Now.AddDays(10), rememberMe, userState.ToString()); string ticketString = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, ticketString); cookie.HttpOnly = true; if (rememberMe) cookie.Expires = DateTime.Now.AddDays(10); var domain = Request.Url.GetBaseDomain(); if (domain != Request.Url.DnsSafeHost) cookie.Domain = domain; HttpContext.Response.Cookies.Add(cookie); } This code works fine on all browsers but Internet Explorer both locally and on full domains. And it also works fine for Internet Explorer with actual 'real' domains. However, this code fails silently for IE when the domain is localhost or any other local address. In that case Internet Explorer simply refuses to accept the cookie and fails to log in. Argh! The end result is that the solution above trying to automatically parse the base domain won't work as local addresses end up failing. Configuration Setting Given this screwed up state of affairs, the best solution to handle this is a configuration setting. Forms Authentication actually has a domain key that can be set for FormsAuthentication so that's natural choice for the storing the domain name: <authentication mode="Forms"> <forms loginUrl="~/Account/Login" name="gnc" domain="mydomain.com" slidingExpiration="true" timeout="30" xdt:Transform="Replace"/> </authentication> Although I'm not actually letting FormsAuth set my cookie directly I can still access the domain name from the static FormsAuthentication.CookieDomain property, by changing the domain assignment code to:if (!string.IsNullOrEmpty(FormsAuthentication.CookieDomain)) cookie.Domain = FormsAuthentication.CookieDomain; The key is to only set the domain when actually running on a full authority, and leaving the domain key blank on the local machine to avoid the local address debacle. Note if you want to see this fail with IE, set the domain to domain="localhost" and watch in Fiddler what happens. Logging Out When specifying a domain key for a login it's also vitally important that that same domain key is used when logging out. Forms Authentication will do this automatically for you when the domain is set and you use FormsAuthentication.SignOut(). If you use an explicit Cookie to manage your logins or other persistant value, make sure that when you log out you also specify the domain. IOW, the expiring cookie you set for a 'logout' should match the same settings - name, path, domain - as the cookie you used to set the value.HttpCookie cookie = new HttpCookie("gne", ""); cookie.Expires = DateTime.Now.AddDays(-5); // make sure we use the same logic to release cookie var domain = Request.Url.GetBaseDomain(); if (domain != Request.Url.DnsSafeHost) cookie.Domain = domain; HttpContext.Response.Cookies.Add(cookie); I managed to get my code to do what I needed it to, but man I'm getting so sick and tired of fixing IE only bugs. I spent most of the day today fixing a number of small IE layout bugs along with this issue which took a bit of time to trace down.© Rick Strahl, West Wind Technologies, 2005-2012Posted in ASP.NET   Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); (function() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/plusone.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); })();

    Read the article

  • Display issue with jQuery dialog: form shows as separate window

    - by RememberME
    On my button click, the jQuery dialog appears with just the title and buttons. When you mouseover, then you see the form inputs in front of the dialog covering the buttons. When you scroll down, the form inputs do not move, so you can never see the last few textboxes. <div id="popupCreateCompany" title="Create a new company"> <form> <fieldset> <p> <label for="company_name">Company Name:</label> <%= Html.TextBox("company_name") %> </p> <p> <label for="company_desc">Company Description:</label> <%= Html.TextBox("company_desc") %> </p> <p> <label for="address">Address:</label> <%= Html.TextBox("address") %> </p> <p> <label for="city">City:</label> <%= Html.TextBox("city") %> </p> <p> <label for="state">State:</label> <%= Html.TextBox("state") %> </p> <p> <label for="zip">Zip:</label> <%= Html.TextBox("zip") %> </p> <p> <label for="website">Website:</label> <%= Html.TextBox("website") %> </p> </fieldset> </form> </div> jQuery: <script type="text/javascript"> $(document).ready(function() { $('input').filter('.datepick').datepicker(); $('#popupCreateCompany').dialog( { autoOpen: false, modal: true, buttons: { 'Add': function() { var dialog = $(this); var form = dialog.find('input:text'); $.post('/company/create', $(form).serialize(), function() { dialog.dialog('close'); }) }, 'Cancel': function() { $(this).dialog('close'); } } }); $("#create-company").click(function() { $('#popupCreateCompany').dialog('open'); }); On mouseover: After scroll down:

    Read the article

  • Creating a new record using AJAX in ASP.NET-MVC

    - by RememberME
    I am having the hardest time wrapping my head around this. I recently asked this question Create/Edit/Save data in a jQuery pop-up for ASP.NET-MVC and Linq2Sql I'm sure that the response is the right way to go, but I just can't figure out how to write the back-end code to make it work. I originally made my site by following the nerddinner tutorial. I have a subcontracts model and a subcontracts controller. On my subcontract entry page, I'd like for there to be a pop-up/dialog box where the user can enter a new company if the company isn't already in the drop-down list. Do I need to create a new company controller? I wouldn't have a company model b/c the company table is linked to my subcontracts table within the subcontracts dbml. Can anyone point me to an example somewhere? Or offer any help.

    Read the article

  • add new option to dropdownlist after jquery dialog and post

    - by RememberME
    I have a form to enter subcontracts. On this form I have a dropdownlist of all companies in the system. Next to it is a button "Create Company". This button opens a jquery dialog which allows the user to create a new company. Once the dialog closes, the new company needs to be added to the dropdownlist and selected. If I refresh, it's there, but I need to do it without refreshing the form b/c I don't want the user to loose everything that they've entered into the other fields. I'm not sure how to do this b/c I don't have the guid of the new company. My jquery dialog: $('#popupCreateCompany').dialog( { autoOpen: false, modal: true, buttons: { 'Add': function() { var dialog = $(this); var form = dialog.find('input:text, select'); $.post('/company/create', $(form).serialize(), function() { dialog.dialog('close'); }) }, 'Cancel': function() { $(this).dialog('close'); } } }); $("#create-company").click(function() { $('#popupCreateCompany').dialog('open'); }); Company field: <label for="company">Company:</label> <%= Html.DropDownList("company", Model.SelectCompanies, "** Select Company **") %> <%= Html.ValidationMessage("Company", "*") %> <button type="button" id="create-company" >Create Company</button>

    Read the article

  • Selected value from drop-down list doesn't post from jquery dialog

    - by RememberME
    I have a jQuery dialog. All of the fields are posting correctly except for the drop-downs, the value is getting passed as null rather than the selected value. <div id="popupCreateCompany" title="Create a new company"> <form> <fieldset> <p> <label for="company_name">Company Name:</label> <%= Html.TextBox("company_name") %> </p> <p> <label for="company_desc">Company Description:</label> <%= Html.TextBox("company_desc") %> </p> <p> <label for="address">Address:</label> <%= Html.TextBox("address") %> </p> <p> <label for="city">City:</label> <%= Html.TextBox("city") %> </p> <p> <label for="state">State:</label> <%= Html.TextBox("state") %> </p> <p> <label for="zip">Zip:</label> <%= Html.TextBox("zip") %> </p> <p> <label for="website">Website:</label> <%= Html.TextBox("website", "http:/") %> </p> <p> <label for="sales_contact">Sales Contact:</label> <%= Html.DropDownList("sales_contact", Model.SelectSalesContacts, "** Select Sales Contact **") %> </p> <p> <label for="primary_company">Primary Company:</label> <%= Html.DropDownList("primary_company", Model.SelectPrimaryCompanies, "** Select Primary Company **") %> </p> </fieldset> </form> jQuery: $('#popupCreateCompany').dialog( { autoOpen: false, modal: true, buttons: { 'Add': function() { var dialog = $(this); var form = dialog.find('input:text'); $.post('/company/create', $(form).serialize(), function() { dialog.dialog('close'); }) }, 'Cancel': function() { $(this).dialog('close'); } } }); $("#create-company").click(function() { $('#popupCreateCompany').dialog('open'); }); My SelectList definitions: public class SubcontractFormViewModel { public subcontract Subcontract { get; private set; } public SelectList SelectPrimaryCompanies { get; set; } public MultiSelectList SelectService_Lines { get; private set; } public SelectList SelectSalesContacts { get; private set; } public SubcontractFormViewModel(subcontract subcontract) { SubcontractRepository subcontractRepository = new SubcontractRepository(); Subcontract = subcontract; SelectPrimaryCompanies = new SelectList(subcontractRepository.GetPrimaryCompanies(), "company_id", "company_name"); SelectService_Lines = new MultiSelectList(subcontractRepository.GetService_Lines(), "service_line_id", "service_line_name", subcontractRepository.GetSubcontractService_Lines(Subcontract.subcontract_id)); SelectSalesContacts = new SelectList(subcontractRepository.GetContacts(), "contact_id", "contact_name"); } }

    Read the article

  • set radio button in jquery dialog

    - by RememberME
    I have the following if/else on another form and it works perfectly. I've now put it on a form which shows as a jquery dialog. Every alert along the way shows the correct assignment, but when the dialog opens, neither button is selected. $("#create-company").click(function() { alert($('#primary_company').val().length); if ($('#primary_company').val().length > 0) { alert("if secondary"); $('#secondary').attr('checked', 'true'); var id = $("input:radio[name='companyType']:checked").attr('id'); alert(id); } else { alert("else primary"); $('#primary').attr('checked', 'true'); $('#sec').hide(); var id = $("input:radio[name='companyType']:checked").attr('id'); alert(id); } var id = $("input:radio[name='companyType']:checked").attr('id'); alert(id); $('#popupCreateCompany').dialog('open'); }); Dialog: $('#popupCreateCompany').dialog( { autoOpen: false, modal: true, buttons: { 'Add': function() { var dialog = $(this); var form = dialog.find('input:text, select'); $.post('/company/post', $(form).serialize(), function(data) { if (data.Result == "success") { var id = $("input:radio[name='companyType']:checked").attr('id'); if (id == "primary") { $('#company').append($('<option></option>').val(data.company_id).html(data.company_name).attr("selected", true)); $('#primary_company').append($('<option></option>').val(data.company_id).html(data.company_name).attr("selected", true)); $('#company_id').append($('<option></option>').val(data.company_id).html(data.company_name).attr("selected", true)); } else { $('#company_id').append($('<option></option>').val(data.company_id).html(data.company_name)); } dialog.dialog('close'); alert("Company " + data.company_name + " successfully added."); } else { alert(data.Result); }; }, "json") }, 'Cancel': function() { $(this).dialog('close'); } } }); Radio buttons: <label>Company Type:</label> <label for="primary"><input onclick="javascript: $('#sec').hide('slow');$('#primary_company').find('option:first').attr('selected','selected');" type="radio" name="companyType" id="primary" />Primary</label> <label for="secondary"><input onclick="javascript: $('#sec').show('slow');" type="radio" name="companyType" id="secondary" />Subsidiary</label> <div id="sec"> <fieldset> <label for="primary_company">Primary Company:</label> <%= Html.DropDownList("primary_company", Model.SelectPrimaryCompanies, "** Select Primary Company **") %> </fieldset> </div>

    Read the article

  • Create/Edit/Save data in a jQuery pop-up for ASP.NET-MVC and Linq2Sql

    - by RememberME
    I have a MVC page which allows creation and editing of a subcontract. When the user has to select a company for the subcontract, I would like for them to have the option to create a new company. I've made a jQuery pop-up with the company fields, but I don't know how to then save this information to the company table. I would also like to be able to use the same pop-up to allow the user to edit the information for an existing company, but need direction in how to send the information to the pop-up.

    Read the article

  • How to write this Link2Sql select query

    - by RememberME
    I have 3 tables: subcontracts, companies and contacts. Each table has a active_status flags which shows that the item is still active (hasn't been deleted). Each contact has a company_id field which stores the id of the contact's company. Each subcontract has a company_id field which stores the subcontract's company. Each company has a company_id field which holds its guid and a primary_company field, b/c the company could be a subsidiary. If it's a subsidiary, the primary_company field holds the id of the primary company. I have a subcontract form. On the form, I have a drop-down of contacts which are stored in a contact table. Currently the drop-down lists all contacts. I would like to have the drop-down only list contacts which belong to the subcontract's company or any of that company's subsidiaries. I have the following query which I use elsewhere in the program to pass a company_id and get its subsidiaries. public IQueryable<company> GetSubsidiaryCompanies(Guid id) { return from c in db.companies where c.primary_company == id && c.active_status == true select c; } This is my current contact selection public IQueryable<contact> GetContacts() { return from c in db.contacts where c.active_status == true orderby c.contact_name select c; } What I need to do is pass it the subcontract.company_id and then only return the contacts where contact.company_id == subcontract.company_id or contact.company_id == one of the subsidiary ids.

    Read the article

1 2 3  | Next Page >