Search Results

Search found 399 results on 16 pages for 'fieldset'.

Page 11/16 | < Previous Page | 7 8 9 10 11 12 13 14 15 16  | Next Page >

  • New Validation Attributes in ASP.NET MVC 3 Future

    - by imran_ku07
         Introduction:             Validating user inputs is an very important step in collecting information from users because it helps you to prevent errors during processing data. Incomplete or improperly formatted user inputs will create lot of problems for your application. Fortunately, ASP.NET MVC 3 makes it very easy to validate most common input validations. ASP.NET MVC 3 includes Required, StringLength, Range, RegularExpression, Compare and Remote validation attributes for common input validation scenarios. These validation attributes validates most of your user inputs but still validation for Email, File Extension, Credit Card, URL, etc are missing. Fortunately, some of these validation attributes are available in ASP.NET MVC 3 Future. In this article, I will show you how to leverage Email, Url, CreditCard and FileExtensions validation attributes(which are available in ASP.NET MVC 3 Future) in ASP.NET MVC 3 application.       Description:             First of all you need to download ASP.NET MVC 3 RTM Source Code from here. Then extract all files in a folder. Then open MvcFutures project from mvc3-rtm-sources\mvc3\src\MvcFutures folder. Build the project. In case, if you get compile time error(s) then simply remove the reference of System.Web.WebPages and System.Web.Mvc assemblies and add the reference of System.Web.WebPages and System.Web.Mvc 3 assemblies again but from the .NET tab and then build the project again, it will create a Microsoft.Web.Mvc assembly inside mvc3-rtm-sources\mvc3\src\MvcFutures\obj\Debug folder. Now we can use Microsoft.Web.Mvc assembly inside our application.             Create a new ASP.NET MVC 3 application. For demonstration purpose, I will create a dummy model UserInformation. So create a new class file UserInformation.cs inside Model folder and add the following code,   public class UserInformation { [Required] public string Name { get; set; } [Required] [EmailAddress] public string Email { get; set; } [Required] [Url] public string Website { get; set; } [Required] [CreditCard] public string CreditCard { get; set; } [Required] [FileExtensions(Extensions = "jpg,jpeg")] public string Image { get; set; } }             Inside UserInformation class, I am using Email, Url, CreditCard and FileExtensions validation attributes which are defined in Microsoft.Web.Mvc assembly. By default FileExtensionsAttribute allows png, jpg, jpeg and gif extensions. You can override this by using Extensions property of FileExtensionsAttribute class.             Then just open(or create) HomeController.cs file and add the following code,   public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(UserInformation u) { return View(); } }             Next just open(or create) Index view for Home controller and add the following code,  @model NewValidationAttributesinASPNETMVC3Future.Model.UserInformation @{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Index</h2> <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>UserInformation</legend> <div class="editor-label"> @Html.LabelFor(model => model.Name) </div> <div class="editor-field"> @Html.EditorFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) </div> <div class="editor-label"> @Html.LabelFor(model => model.Email) </div> <div class="editor-field"> @Html.EditorFor(model => model.Email) @Html.ValidationMessageFor(model => model.Email) </div> <div class="editor-label"> @Html.LabelFor(model => model.Website) </div> <div class="editor-field"> @Html.EditorFor(model => model.Website) @Html.ValidationMessageFor(model => model.Website) </div> <div class="editor-label"> @Html.LabelFor(model => model.CreditCard) </div> <div class="editor-field"> @Html.EditorFor(model => model.CreditCard) @Html.ValidationMessageFor(model => model.CreditCard) </div> <div class="editor-label"> @Html.LabelFor(model => model.Image) </div> <div class="editor-field"> @Html.EditorFor(model => model.Image) @Html.ValidationMessageFor(model => model.Image) </div> <p> <input type="submit" value="Save" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div>             Now just run your application. You will find that both client side and server side validation for the above validation attributes works smoothly.                      Summary:             Email, URL, Credit Card and File Extension input validations are very common. In this article, I showed you how you can validate these input validations into your application. I explained this with an example. I am also attaching a sample application which also includes Microsoft.Web.Mvc.dll. So you can add a reference of Microsoft.Web.Mvc assembly directly instead of doing any manual work. Hope you will enjoy this article too.   SyntaxHighlighter.all()

    Read the article

  • ASP.NET MVC 3 Hosting :: MVC 2 Strongly Typed HTML Helper and Enhanced Validation Sample

    - by mbridge
    In lue of the off the official release of ASP.NET MVC 2 RTM, I decided I would put together a quick sample of the enhanced HTML.Helpers and validation controls. I am going to use my sample event site where I will have a form so a user can search for information about a certain events. So when the Search page loads the Search action is fired return my strongly typed model. to the view.    1: [HttpGet]    2: public ViewResult Search(): public ViewResult Search()    3: {    4:     IList<EventsModel> result = _eventsService.GetEventList();    5:     var viewModel = new EventSearchModel    6:                         {    7:                             EventList = new SelectList(result, "EventCode","EventName","Select Event")    8:                         };    9:     return View(viewModel);  10: } Nothing special here, although I did want to show how to load up a strongly typed drop down list because that hung me up for a little bit. So to that, I am going to pass back a SelectList to the view and my HTML helper should no how to load this. So lets take a look at the mark up for the view.    1: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"    2: Inherits="System.Web.Mvc.ViewPage<EventsSample.Models.EventSearchModel>" %>    3:     4: <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">    5:     Search    6: </asp:Content>    7:     8: <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">    9:   10:     <h2>Search for Events</h2>  11:   12:     <% using (Html.BeginForm("Search","Events")) {%>  13:         <%= Html.ValidationSummary(true) %>  14:          15:         <fieldset>  16:             <legend>Fields</legend>  17:              18:             <div class="editor-label">  19:                 <%= Html.LabelFor(model => model.EventNumber) %>  20:             </div>  21:             <div class="editor-field">  22:                 <%= Html.TextBoxFor(model => model.EventNumber) %>  23:                 <%= Html.ValidationMessageFor(model => model.EventNumber) %>  24:             </div>  25:              26:             <div class="editor-label">  27:                 <%= Html.LabelFor(model => model.GuestLastName) %>  28:             </div>  29:             <div class="editor-field">  30:                 <%= Html.TextBoxFor(model => model.GuestLastName) %>  31:                 <%= Html.ValidationMessageFor(model => model.GuestLastName) %>  32:             </div>  33:              34:             <div class="editor-label">  35:                 <%= Html.LabelFor(model => model.EventName) %>  36:             </div>  37:             <div class="editor-field">  38:                 <%= Html.DropDownListFor(model => model.EventName, Model.EventList,"Select Event") %>  39:                 <%= Html.ValidationMessageFor(model => model.EventName) %>  40:             </div>  41:              42:             <p>  43:                 <input type="submit" value="Save" />  44:             </p>  45:         </fieldset>  46:   47:     <% } %>  48:   49:     <div>  50:         <%= Html.ActionLink("Back to List", "Index") %>  51:     </div>  52:   53: </asp:Content> A nice feature is the scaffolding that MVC has to generate code. I simply right clicked inside my Search() action, inside the EventsController and selected “Add View” and then I selected my strongly typed object that I wanted to pass to the view and also selected that I wanted the content type be “Edit”. With that the aspx page was completely generated, although I did have to go back in and change the textbox for the Event Names to a drop down list of the names to select from. The new feature with MVC 2 are the strongly typed HTML helpers. So now, my textboxes, drop down list, and validation helpers are all strongly typed to my model.  This features gives you the benefits of intellisense and also makes it easier to debug. “The Gu” has a great post about the feature in case you want more details. The DropDownListFor function to generate the drop down list was a little tricky for me. You first need to use a Lanbda expression to pass in the property you want the selected value assigned to in your model, and then you need to pass in the list directly from the model. Validations To validate the form, you can use the strongly type validation HTML helpers which will inspect your model and return errors if the validation fails. The definitions of these rules are set directly on the Model itself so lets take a look.    1: using System.ComponentModel.DataAnnotations;    2: using System.Web.Mvc;    3:     4: namespace EventsSample.Models    5: {    6:     public class EventSearchModel    7:     {    8:         [Required(ErrorMessage = "Please enter the event number.")]    9:         [RegularExpression(@"\w{6}",  10:             ErrorMessage = "The Event Number must be 6 letters and/or numbers.")]  11:         public string EventNumber { get; set; }  12:   13:         [Required(ErrorMessage = "Please enter the guest's last name.")]  14:         [RegularExpression(@"^[A-Za-zÀ-ÖØ-öø-ÿ1-9 '\-\.]{1,22}$",  15:             ErrorMessage = "The gueest's last name must 1 to 20 characters.")]  16:         public string GuestLastName { get; set; }  17:   18:         public string EventName { get; set; }  19:         public SelectList EventList { get; set; }  20:     }  21: } Pretty cool! Okay, the only thing left to do is perform the validation in the POST action.    1: [HttpPost]    2: public ViewResult Search(EventSearchModel eventSearchModel)    3: {    4:     if (ModelState.IsValid) return View("SearchResults");    5:     else    6:     {    7:          IList<EventsModel> result = _eventsService.GetEventList();    8:         eventSearchModel.EventList = new SelectList(result, "EVentCode","EventName");   9:   10:         return View(eventSearchModel);  11:     }  12: }  13:     } If the form entries are valid, here I am simply displaying the SearchResult, but in a real world sample I would also go out get the results first. You get the idea though. In my case, when the form is not valid, I also had to reload my SelectList with the event names before I loaded the page again. Remember this is MVC, no _VieState here :) So that’s it. Now my form is validating the data and when it fails it looks like this.

    Read the article

  • pagination for displaytag with colorbox in Spring framework

    - by Hitesh Solanki
    Hi..... I want to display the pop up for user selection using colorbox. I have put link on manageblacklist.jsp named 'select'. when I click on 'select' link ,colorbox is displayed. all user is displayed but pagination is not worked. I have used display tag for pagination. Without using colorbox, pagination is worked fine. I have used spring framework. The code of manageblacklist.jsp is given below: <%@ page contentType="text/html" pageEncoding="UTF-8" import="java.util.*"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ include file="/WEB-INF/jsp/include.jsp" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ taglib uri="http://displaytag.sf.net" prefix="display" %> <%@ page import="com.sufalam.mailserver.bean.User"%> <%@ page import="javax.servlet.http.HttpSession" %> <% String pageSize = (String) request.getAttribute("pageSize"); System.out.println("page size:" + pageSize); HttpSession session1 = request.getSession(); List<User> userList = (List<User>) session1.getAttribute("userList"); Iterator iterator = userList.iterator(); String user = (String) request.getAttribute("user"); System.out.println("user in the jsp :" + user); %> <html> <head> <script type="text/javascript" src="js/jquery142.js"></script> <script type="text/javascript" src="js/jquery.colorbox.js"></script> <link rel="stylesheet" href="style/colorbox.css" type="text/css"> <script type="text/javascript"> $(document).ready(function(){ //Examples of how to assign the ColorBox event to elements $(".example5").colorbox(); //Example of preserving a JavaScript event for inline calls. $("#click").click(function(){ $('#click').css({"background-color":"#f00", "color":"#fff", "cursor":"inherit"}).text("Open this window again and this message will still be here."); return false; }); }); </script> <script type="text/javascript"> function changePageSize() { var myValue = document.getElementById("combo1").value; document.getElementById("selectedPageSize").value=myValue; document.whitelistBlacklistForm.submit(); } function selectAll() { var selectAll = document.getElementById("checkAll"); var returnById = document.getElementsByName("check"); var i; var val; if (selectAll.checked == true) { val = true; } else { val = false; } for (i = 0; i < returnById.length; i++) { returnById[i].checked = val; } } function onload() { insertNavigation ('insertHereTop', 'insertHereBottom'); } function insertNavigation( topElementID, BottomElementID ) { if ( document.getElementById('pagingBanner') ){ document.getElementById(topElementID).innerHTML=document.getElementById('pagingBanner').innerHTML; document.getElementById(BottomElementID).innerHTML=document.getElementById('pagingBanner1').innerHTML; } } function confirmDelete() { if (confirm("Are you sure you want to delete selected records?")) { flag = 1; return true; } else { return false; } } function loadModels() { var flag=true; var textValue = document.getElementById('txtuser'); $.getJSON("ajaxblacklist.htm", // url { param :textValue.value }, // request params function(json) { // callback // var options = '<table class="displayTable" cellspacing="0"><thead><tr><th align = "center">Blacklisted Sender</th>'+ // '<th align ="center">Delete</th></tr></thead><tbody>'; var options = '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td style="background:url(images/leftbg.gif) repeat-y; width:8px;"></td>' + '<td class="middlesection"><table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>' + '<td height="30" class="p10"><table width="100%" border="0" cellspacing="0" cellpadding="0" class="allboder" >' + '<tr><td class="tebelhd"> Blacklisted Sender </td></tr>'; for (i in json) { var state = json[i]; for(j in state){ var op = state[j]; if(op.length==undefined){ options += '<tr><td class="tdhd"><table width="0%" border="0" cellspacing="0" cellpadding="0"><tr><td width="741">'+ state[j].senderEmail + '</td><td align="center" width="148"><a href="managewhitelistblacklist.htm?sender='+state[j].senderEmail+'&recipient='+ state[j].recipientEmail+'&action=delete"><span> <img src="/MailServerV2/images/delete.gif"/> </span></a></td></tr></table></td></tr>'; break; } for(k in op) { if(flag == true) { flag = false; options += '<tr><td class="tdhd"><table width="0%" border="0" cellspacing="0" cellpadding="0"><tr>'; } else { flag = true; options += '<tr><td class="tdhd2"><table width="0%" border="0" cellspacing="0" cellpadding="0"><tr>'; } options += '<td width="741">'+ op[k].senderEmail +'</td><td align="center" width="148"><a href="managewhitelistblacklist.htm?sender='+op[k].senderEmail+'&recipient='+op[k].recipientEmail+'&action=delete"><span> <img src="/MailServerV2/images/delete.gif"/> </span></a></td></tr></table></td></tr>'; } } } options += '</td></tr></table>'; $("div[name^=blacklist]").html(options); }); } </script> </head> <body> <table width="" border="0" align="center" cellpadding="0" cellspacing="0" class="maintable"> <tr> <td class="topsection"><table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td valign="top" align="center" class="middlesection" ><table width="96%" border="0" cellspacing="0" cellpadding="0"> <tr> <td >&nbsp;</td> </tr> <tr> <td> <table width="100%" border="0" cellspacing ="0" cellpadding="0"> <tr> <td> <table width="100%" border="0" cellspacing="0" cellpadding="3"> <tr> <td align="left" valign="middle"><h1>Manage Blacklist</h1></td> <td align="right" valign="bottom"><div style="float:right;"><a href="savewhitelistblacklist.htm" class="buttonash"><span>Create Whitelist Blacklist </span></a></div></td> </tr> </table></td> </tr> <tr> <td class="bottomboder"><img src="images/ashish.gif" height="1" /></td> </tr> </table> </td> </tr> <tr> <td>&nbsp;</td> </tr> <tr> <td> </td> </tr> <tr> <td> <div id="TabbedPanels1" class="TabbedPanels"/> <div style="display: block;" class="TabbedPanelsContent"/> <div align="left" class="tebelhd"> Blacklist Information </div><div class="entry-edit"> <div class="fieldset" id="base_fieldset"> <div class="hor-scroll_1" align="left"> <fieldset Class="label1css" style="color:#666666"> <legend>Fields</legend> <table> <tr> <td align="right"> Recipient Email : </td> <td><input type="text" id="txtuser" name="txtuser" <% if (user != null) { %> value="<%=user%>" <% } else { %> value="" <% } %> /> </td> <td><a href="#" class="buttonash" onclick="loadModels()"><span>Search</span></a></td> <!-- <td><a href="javascript:void(0)" class="buttonash" onclick="window.open('selectuser.htm','selectuser','width=600,height=400,menubar=yes,status=yes,location=yes,toolbar=yes,scrollbars=yes');" ><span>Select</span></a></td>--> <td><a href="selectuser.htm" class="example5 buttonash" ><span>Select</span></a> </td> <td align="right"> </td> </tr> </table> </fieldset> <div id="blacklist" name="blacklist"></div> </div> </div> </div> </td> </tr> </table> </td> </tr> </table> </td> <!-- InstanceEndEditable --> <td style="background:url(images/rightbg.gif) repeat-y; width:8px;"></td> </tr> </table> <% // session1.removeAttribute("user"); %> </body> </html> So , please tell me how to work pagination .... Thanks in advanced...

    Read the article

  • Using LINQ Distinct: With an Example on ASP.NET MVC SelectListItem

    - by Joe Mayo
    One of the things that might be surprising in the LINQ Distinct standard query operator is that it doesn’t automatically work properly on custom classes. There are reasons for this, which I’ll explain shortly. The example I’ll use in this post focuses on pulling a unique list of names to load into a drop-down list. I’ll explain the sample application, show you typical first shot at Distinct, explain why it won’t work as you expect, and then demonstrate a solution to make Distinct work with any custom class. The technologies I’m using are  LINQ to Twitter, LINQ to Objects, Telerik Extensions for ASP.NET MVC, ASP.NET MVC 2, and Visual Studio 2010. The function of the example program is to show a list of people that I follow.  In Twitter API vernacular, these people are called “Friends”; though I’ve never met most of them in real life. This is part of the ubiquitous language of social networking, and Twitter in particular, so you’ll see my objects named accordingly. Where Distinct comes into play is because I want to have a drop-down list with the names of the friends appearing in the list. Some friends are quite verbose, which means I can’t just extract names from each tweet and populate the drop-down; otherwise, I would end up with many duplicate names. Therefore, Distinct is the appropriate operator to eliminate the extra entries from my friends who tend to be enthusiastic tweeters. The sample doesn’t do anything with the drop-down list and I leave that up to imagination for what it’s practical purpose could be; perhaps a filter for the list if I only want to see a certain person’s tweets or maybe a quick list that I plan to combine with a TextBox and Button to reply to a friend. When the program runs, you’ll need to authenticate with Twitter, because I’m using OAuth (DotNetOpenAuth), for authentication, and then you’ll see the drop-down list of names above the grid with the most recent tweets from friends. Here’s what the application looks like when it runs: As you can see, there is a drop-down list above the grid. The drop-down list is where most of the focus of this article will be. There is some description of the code before we talk about the Distinct operator, but we’ll get there soon. This is an ASP.NET MVC2 application, written with VS 2010. Here’s the View that produces this screen: <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TwitterFriendsViewModel>" %> <%@ Import Namespace="DistinctSelectList.Models" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">     Home Page </asp:Content><asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">     <fieldset>         <legend>Twitter Friends</legend>         <div>             <%= Html.DropDownListFor(                     twendVM => twendVM.FriendNames,                     Model.FriendNames,                     "<All Friends>") %>         </div>         <div>             <% Html.Telerik().Grid<TweetViewModel>(Model.Tweets)                    .Name("TwitterFriendsGrid")                    .Columns(cols =>                     {                         cols.Template(col =>                             { %>                                 <img src="<%= col.ImageUrl %>"                                      alt="<%= col.ScreenName %>" />                         <% });                         cols.Bound(col => col.ScreenName);                         cols.Bound(col => col.Tweet);                     })                    .Render(); %>         </div>     </fieldset> </asp:Content> As shown above, the Grid is from Telerik’s Extensions for ASP.NET MVC. The first column is a template that renders the user’s Avatar from a URL provided by the Twitter query. Both the Grid and DropDownListFor display properties that are collections from a TwitterFriendsViewModel class, shown below: using System.Collections.Generic; using System.Web.Mvc; namespace DistinctSelectList.Models { /// /// For finding friend info on screen /// public class TwitterFriendsViewModel { /// /// Display names of friends in drop-down list /// public List FriendNames { get; set; } /// /// Display tweets in grid /// public List Tweets { get; set; } } } I created the TwitterFreindsViewModel. The two Lists are what the View consumes to populate the DropDownListFor and Grid. Notice that FriendNames is a List of SelectListItem, which is an MVC class. Another custom class I created is the TweetViewModel (the type of the Tweets List), shown below: namespace DistinctSelectList.Models { /// /// Info on friend tweets /// public class TweetViewModel { /// /// User's avatar /// public string ImageUrl { get; set; } /// /// User's Twitter name /// public string ScreenName { get; set; } /// /// Text containing user's tweet /// public string Tweet { get; set; } } } The initial Twitter query returns much more information than we need for our purposes and this a special class for displaying info in the View.  Now you know about the View and how it’s constructed. Let’s look at the controller next. The controller for this demo performs authentication, data retrieval, data manipulation, and view selection. I’ll skip the description of the authentication because it’s a normal part of using OAuth with LINQ to Twitter. Instead, we’ll drill down and focus on the Distinct operator. However, I’ll show you the entire controller, below,  so that you can see how it all fits together: using System.Linq; using System.Web.Mvc; using DistinctSelectList.Models; using LinqToTwitter; namespace DistinctSelectList.Controllers { [HandleError] public class HomeController : Controller { private MvcOAuthAuthorization auth; private TwitterContext twitterCtx; /// /// Display a list of friends current tweets /// /// public ActionResult Index() { auth = new MvcOAuthAuthorization(InMemoryTokenManager.Instance, InMemoryTokenManager.AccessToken); string accessToken = auth.CompleteAuthorize(); if (accessToken != null) { InMemoryTokenManager.AccessToken = accessToken; } if (auth.CachedCredentialsAvailable) { auth.SignOn(); } else { return auth.BeginAuthorize(); } twitterCtx = new TwitterContext(auth); var friendTweets = (from tweet in twitterCtx.Status where tweet.Type == StatusType.Friends select new TweetViewModel { ImageUrl = tweet.User.ProfileImageUrl, ScreenName = tweet.User.Identifier.ScreenName, Tweet = tweet.Text }) .ToList(); var friendNames = (from tweet in friendTweets select new SelectListItem { Text = tweet.ScreenName, Value = tweet.ScreenName }) .Distinct() .ToList(); var twendsVM = new TwitterFriendsViewModel { Tweets = friendTweets, FriendNames = friendNames }; return View(twendsVM); } public ActionResult About() { return View(); } } } The important part of the listing above are the LINQ to Twitter queries for friendTweets and friendNames. Both of these results are used in the subsequent population of the twendsVM instance that is passed to the view. Let’s dissect these two statements for clarification and focus on what is happening with Distinct. The query for friendTweets gets a list of the 20 most recent tweets (as specified by the Twitter API for friend queries) and performs a projection into the custom TweetViewModel class, repeated below for your convenience: var friendTweets = (from tweet in twitterCtx.Status where tweet.Type == StatusType.Friends select new TweetViewModel { ImageUrl = tweet.User.ProfileImageUrl, ScreenName = tweet.User.Identifier.ScreenName, Tweet = tweet.Text }) .ToList(); The LINQ to Twitter query above simplifies what we need to work with in the View and the reduces the amount of information we have to look at in subsequent queries. Given the friendTweets above, the next query performs another projection into an MVC SelectListItem, which is required for binding to the DropDownList.  This brings us to the focus of this blog post, writing a correct query that uses the Distinct operator. The query below uses LINQ to Objects, querying the friendTweets collection to get friendNames: var friendNames = (from tweet in friendTweets select new SelectListItem { Text = tweet.ScreenName, Value = tweet.ScreenName }) .Distinct() .ToList(); The above implementation of Distinct seems normal, but it is deceptively incorrect. After running the query above, by executing the application, you’ll notice that the drop-down list contains many duplicates.  This will send you back to the code scratching your head, but there’s a reason why this happens. To understand the problem, we must examine how Distinct works in LINQ to Objects. Distinct has two overloads: one without parameters, as shown above, and another that takes a parameter of type IEqualityComparer<T>.  In the case above, no parameters, Distinct will call EqualityComparer<T>.Default behind the scenes to make comparisons as it iterates through the list. You don’t have problems with the built-in types, such as string, int, DateTime, etc, because they all implement IEquatable<T>. However, many .NET Framework classes, such as SelectListItem, don’t implement IEquatable<T>. So, what happens is that EqualityComparer<T>.Default results in a call to Object.Equals, which performs reference equality on reference type objects.  You don’t have this problem with value types because the default implementation of Object.Equals is bitwise equality. However, most of your projections that use Distinct are on classes, just like the SelectListItem used in this demo application. So, the reason why Distinct didn’t produce the results we wanted was because we used a type that doesn’t define its own equality and Distinct used the default reference equality. This resulted in all objects being included in the results because they are all separate instances in memory with unique references. As you might have guessed, the solution to the problem is to use the second overload of Distinct that accepts an IEqualityComparer<T> instance. If you were projecting into your own custom type, you could make that type implement IEqualityComparer<T>, but SelectListItem belongs to the .NET Framework Class Library.  Therefore, the solution is to create a custom type to implement IEqualityComparer<T>, as in the SelectListItemComparer class, shown below: using System.Collections.Generic; using System.Web.Mvc; namespace DistinctSelectList.Models { public class SelectListItemComparer : EqualityComparer { public override bool Equals(SelectListItem x, SelectListItem y) { return x.Value.Equals(y.Value); } public override int GetHashCode(SelectListItem obj) { return obj.Value.GetHashCode(); } } } The SelectListItemComparer class above doesn’t implement IEqualityComparer<SelectListItem>, but rather derives from EqualityComparer<SelectListItem>. Microsoft recommends this approach for consistency with the behavior of generic collection classes. However, if your custom type already derives from a base class, go ahead and implement IEqualityComparer<T>, which will still work. EqualityComparer is an abstract class, that implements IEqualityComparer<T> with Equals and GetHashCode abstract methods. For the purposes of this application, the SelectListItem.Value property is sufficient to determine if two items are equal.   Since SelectListItem.Value is type string, the code delegates equality to the string class. The code also delegates the GetHashCode operation to the string class.You might have other criteria in your own object and would need to define what it means for your object to be equal. Now that we have an IEqualityComparer<SelectListItem>, let’s fix the problem. The code below modifies the query where we want distinct values: var friendNames = (from tweet in friendTweets select new SelectListItem { Text = tweet.ScreenName, Value = tweet.ScreenName }) .Distinct(new SelectListItemComparer()) .ToList(); Notice how the code above passes a new instance of SelectListItemComparer as the parameter to the Distinct operator. Now, when you run the application, the drop-down list will behave as you expect, showing only a unique set of names. In addition to Distinct, other LINQ Standard Query Operators have overloads that accept IEqualityComparer<T>’s, You can use the same techniques as shown here, with SelectListItemComparer, with those other operators as well. Now you know how to resolve problems with getting Distinct to work properly and also have a way to fix problems with other operators that require equality comparisons. @JoeMayo

    Read the article

  • Preventing duplicate Data with ASP.NET AJAX

    - by Yousef_Jadallah
      Some times you need to prevent  User names ,E-mail ID's or other values from being duplicated by a new user during Registration or any other cases,So I will add a simple approach to make the page more user-friendly. Instead the user filled all the Registration fields then press submit after that received a message as a result of PostBack that "THIS USERNAME IS EXIST", Ajax tidies this up by allowing asynchronous querying while the user is still completing the registration form.   ASP.NET enables you to create Web services can be accessed from client script in Web pages by using AJAX technology to make Web service calls. Data is exchanged asynchronously between client and server, typically in JSON format. I’ve added an article to show you step by step  how to use ASP.NET AJAX with Web Services , you can find it here .   Lets go a head with the steps :   1-Create a new project , if you are using VS 2005 you have to create ASP.NET Ajax Enabled Web site.   2-Create your own Database which contain user table that have User_Name field. for Testing I’ve added SQL Server Database that come with Dot Net 2008: Then I’ve created tblUsers:   This table and this structure just for our example, you can use your own table to implement this approach.   3-Add new Item to your project or website, Choose Web Service file, lets say  WebService.cs  .In this Web Service file import System.Data.SqlClient Namespace, Then Add your web method that contain string parameter which received the Username parameter from the Script , Finally don’t forget to qualified the Web Service Class with the ScriptServiceAttribute attribute ([System.Web.Script.Services.ScriptService])     using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data.SqlClient;     [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService {     [WebMethod] public int CheckDuplicate(string User_Name) { string strConn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestDB.mdf;Integrated Security=True;User Instance=True"; string strQuery = "SELECT COUNT(*) FROM tblUsers WHERE User_Name = @User_Name"; SqlConnection con = new SqlConnection(strConn); SqlCommand cmd = new SqlCommand(strQuery, con); cmd.Parameters.Add("User_Name", User_Name); con.Open(); int RetVal= (int)cmd.ExecuteScalar(); con.Close(); return RetVal; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   Our Web Method here is CheckDuplicate Which accept User_Name String as a parameter and return number of the rows , if the name will found in the database this method will return 1 else it will return 0. I’ve applied  [WebMethod] Attribute to our method CheckDuplicate, And applied the ScriptService attribute to a Web Service class named WebService.   4-Add this simple Registration form : <fieldset> <table id="TblRegistratoin" cellpadding="0" cellspacing="0"> <tr> <td> User Name </td> <td> <asp:TextBox ID="txtUserName" onblur="CallWebMethod();" runat="server"></asp:TextBox> </td> <td> <asp:Label ID="lblDuplicate" runat="server" ForeColor="Red" Text=""></asp:Label> </td> </tr> <tr> <td colspan="3"> <asp:Button ID="btnRegistration" runat="server" Text="Registration" /> </td> </tr> </table> </fieldset> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   onblur event is added to the Textbox txtUserName, This event Fires when the Textbox loses the input focus, That mean after the user get focus out from the Textbox CallWebMethod function will be fired. CallWebMethod will be implemented in step 6.   5-Add ScriptManager Control to your aspx file then reference the Web service by adding an asp:ServiceReference child element to the ScriptManager control and setting its path attribute to point to the Web service, That generate a JavaScript proxy class for calling the specified Web service from client script.   <asp:ScriptManager runat="server" ID="scriptManager"> <Services> <asp:ServiceReference Path="WebService.asmx" /> </Services> </asp:ScriptManager> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }     6-Define the JavaScript code to call the Web Service :   <script language="javascript" type="text/javascript">   // This function calls the Web service method // passing simple type parameters and the // callback function function CallWebMethod() { var User_Name = document.getElementById('<%=txtUserName.ClientID %>').value; WebService.CheckDuplicate(User_Name, OnSucceeded, OnError); }   // This is the callback function invoked if the Web service // succeeded function OnSucceeded(result) { var rsltElement = document.getElementById("lblDuplicate"); if (result == 1) rsltElement.innerHTML = "This User Name is exist"; else rsltElement.innerHTML = "";   }   function OnError(error) { // Display the error. alert("Service Error: " + error.get_message()); } </script> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   This call references the WebService Class and CheckDuplicate Web Method defined in the service. It passes a User_Name value obtained from a textbox as well as a callback function named OnSucceeded that should be invoked when the asynchronous Web Service call returns. If the Web Service in different Namespace you can refer it before the class name this Main formula may help you :  NameSpaceName.ClassName.WebMethdName(Parameters , Success callback function, Error callback function); Parameters: you can pass one or many parameters. Success callback function :handles returned data from the service . Error callback function :Any errors that occur when the Web Service is called will trigger in this function. Using Error Callback function is optional.   Hope these steps help you to understand this approach.

    Read the article

  • Preventing duplicate Data with ASP.NET AJAX

    - by Yousef_Jadallah
      Some times you need to prevent  User names ,E-mail ID's or other values from being duplicated by a new user during Registration or any other cases,So I will add a simple approach to make the page more user-friendly. Instead the user filled all the Registration fields then press submit after that received a message as a result of PostBack that "THIS USERNAME IS EXIST", Ajax tidies this up by allowing asynchronous querying while the user is still completing the registration form.   ASP.NET enables you to create Web services can be accessed from client script in Web pages by using AJAX technology to make Web service calls. Data is exchanged asynchronously between client and server, typically in JSON format. I’ve added an article to show you step by step  how to use ASP.NET AJAX with Web Services , you can find it here .   Lets go a head with the steps :   1-Create a new project , if you are using VS 2005 you have to create ASP.NET Ajax Enabled Web site.   2-Create your own Database which contain user table that have User_Name field. for Testing I’ve added SQL Server Database that come with Dot Net 2008: Then I’ve created tblUsers:   This table and this structure just for our example, you can use your own table to implement this approach.   3-Add new Item to your project or website, Choose Web Service file, lets say  WebService.cs  .In this Web Service file import System.Data.SqlClient Namespace, Then Add your web method that contain string parameter which received the Username parameter from the Script , Finally don’t forget to qualified the Web Service Class with the ScriptServiceAttribute attribute ([System.Web.Script.Services.ScriptService])     using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; using System.Data.SqlClient;     [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.Web.Script.Services.ScriptService] public class WebService : System.Web.Services.WebService {     [WebMethod] public int CheckDuplicate(string User_Name) { string strConn = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\TestDB.mdf;Integrated Security=True;User Instance=True"; string strQuery = "SELECT COUNT(*) FROM tblUsers WHERE User_Name = @User_Name"; SqlConnection con = new SqlConnection(strConn); SqlCommand cmd = new SqlCommand(strQuery, con); cmd.Parameters.Add("User_Name", User_Name); con.Open(); int RetVal= (int)cmd.ExecuteScalar(); con.Close(); return RetVal; } } .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   Our Web Method here is CheckDuplicate Which accept User_Name String as a parameter and return number of the rows , if the name will found in the database this method will return 1 else it will return 0. I’ve applied  [WebMethod] Attribute to our method CheckDuplicate, And applied the ScriptService attribute to a Web Service class named WebService.   4-Add this simple Registration form : <fieldset> <table id="TblRegistratoin" cellpadding="0" cellspacing="0"> <tr> <td> User Name </td> <td> <asp:TextBox ID="txtUserName" onblur="CallWebMethod();" runat="server"></asp:TextBox> </td> <td> <asp:Label ID="lblDuplicate" runat="server" ForeColor="Red" Text=""></asp:Label> </td> </tr> <tr> <td colspan="3"> <asp:Button ID="btnRegistration" runat="server" Text="Registration" /> </td> </tr> </table> </fieldset> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   onblur event is added to the Textbox txtUserName, This event Fires when the Textbox loses the input focus, That mean after the user get focus out from the Textbox CallWebMethod function will be fired. CallWebMethod will be implemented in step 6.   5-Add ScriptManager Control to your aspx file then reference the Web service by adding an asp:ServiceReference child element to the ScriptManager control and setting its path attribute to point to the Web service, That generate a JavaScript proxy class for calling the specified Web service from client script.   <asp:ScriptManager runat="server" ID="scriptManager"> <Services> <asp:ServiceReference Path="WebService.asmx" /> </Services> </asp:ScriptManager> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }     6-Define the JavaScript code to call the Web Service :   <script language="javascript" type="text/javascript">   // This function calls the Web service method // passing simple type parameters and the // callback function function CallWebMethod() { var User_Name = document.getElementById('<%=txtUserName.ClientID %>').value; WebService.CheckDuplicate(User_Name, OnSucceeded, OnError); }   // This is the callback function invoked if the Web service // succeeded function OnSucceeded(result) { var rsltElement = document.getElementById("lblDuplicate"); if (result == 1) rsltElement.innerHTML = "This User Name is exist"; else rsltElement.innerHTML = "";   }   function OnError(error) { // Display the error. alert("Service Error: " + error.get_message()); } </script> .csharpcode, .csharpcode pre { font-size: small; color: black; font-family: consolas, "Courier New", courier, monospace; background-color: #ffffff; /*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt { background-color: #f4f4f4; width: 100%; margin: 0em; } .csharpcode .lnum { color: #606060; }   This call references the WebService Class and CheckDuplicate Web Method defined in the service. It passes a User_Name value obtained from a textbox as well as a callback function named OnSucceeded that should be invoked when the asynchronous Web Service call returns. If the Web Service in different Namespace you can refer it before the class name this Main formula may help you :  NameSpaceName.ClassName.WebMethdName(Parameters , Success callback function, Error callback function); Parameters: you can pass one or many parameters. Success callback function :handles returned data from the service . Error callback function :Any errors that occur when the Web Service is called will trigger in this function. Using Error Callback function is optional.   Hope these steps help you to understand this approach.

    Read the article

  • ASP.NET MVC File Upload Error - "The input is not a valid Base-64 string"

    - by Justin
    Hey all, I'm trying to add a file upload control to my ASP.NET MVC 2 form but after I select a jpg and click Save, it gives the following error: The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or a non-white space character among the padding characters. Here's the view: <% using (Html.BeginForm("Save", "Developers", FormMethod.Post, new {enctype = "multipart/form-data"})) { %> <%: Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div class="editor-label"> Login Name </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.LoginName) %> <%: Html.ValidationMessageFor(model => model.LoginName) %> </div> <div class="editor-label"> Password </div> <div class="editor-field"> <%: Html.Password("Password") %> <%: Html.ValidationMessageFor(model => model.Password) %> </div> <div class="editor-label"> First Name </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.FirstName) %> <%: Html.ValidationMessageFor(model => model.FirstName) %> </div> <div class="editor-label"> Last Name </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.LastName) %> <%: Html.ValidationMessageFor(model => model.LastName) %> </div> <div class="editor-label"> Photo </div> <div class="editor-field"> <input id="Photo" name="Photo" type="file" /> </div> <p> <%: Html.Hidden("DeveloperID") %> <%: Html.Hidden("CreateDate") %> <input type="submit" value="Save" /> </p> </fieldset> <% } %> And the controller: //POST: /Secure/Developers/Save/ [AcceptVerbs(HttpVerbs.Post)] public ActionResult Save(Developer developer) { //get profile photo. var upload = Request.Files["Photo"]; if (upload.ContentLength > 0) { string savedFileName = Path.Combine( ConfigurationManager.AppSettings["FileUploadDirectory"], "Developer_" + developer.FirstName + "_" + developer.LastName + ".jpg"); upload.SaveAs(savedFileName); } developer.UpdateDate = DateTime.Now; if (developer.DeveloperID == 0) {//inserting new developer. DataContext.DeveloperData.Insert(developer); } else {//attaching existing developer. DataContext.DeveloperData.Attach(developer); } //save changes. DataContext.SaveChanges(); //redirect to developer list. return RedirectToAction("Index"); } Thanks, Justin

    Read the article

  • ASP.NET MVC2 Model Validation Fails with Non-US Date Format

    - by 81bronco
    I have a small MVC2 app that displays in two cultures: en-US and es-MX. One portion contains a user input for a date that is pre-populated with the current date in the Model. When using en-US, the date field is displayed as MM/dd/yyyy and can be changed using the same format without causing any validation errors. When using es-MX, the date field is displayed as dd/MM/yyyy, but when the date is edited in this format, the server-side validation fails with the message: The value '17/05/1991' is not valid for The Date. One of the first things that jumps out at me about that message is that it is not localized. Both the message itself (which I do not think I can control) and the Display Name of the field (which I can control and is localized in my code). Should be displaying in a localized format. I have tried stepping through the code to see exactly where the validation is failing, but it seems to be happening inside some of the compiled MVC or DataAnnotations code that I cannot see. Application details: IIS6, ASP.NET 3.5 (C#), MVC 2 RTM Sample Model Code: public class TestVieModel{ [LocalizedDisplayNameDisplayName("TheDateDisplayName", NameResourceType=typeof(Resources.Model.TestViewModel))] [Required(ErrorMessageResourceName="TheDateValidationMessageRequired", ErrorMessageResourceType=typeof(Resources.Model.TestViewModel))] [DataType(DataType.Date)] public DateTime TheDate { get; set; } } Sample Controller Action Code: [HttpPost] [ValidateAntiForgeryToken] public ActionResult Save(TestViewModel model) { if(ModelState.IsValid) { // <--- Always is false when using es-MX and a date foramtted as dd/MM/yyyy. // Do other stuff return this.View("Complete", model); } // Validation failed, redisplay the form. return this.View("Enter", model); } Sample View Code: <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<HispanicSweeps.Web.Model.LosMets.EnterViewModel>" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Test</title> </head> <body> <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div class="editor-label"> <%= Html.LabelFor(model => model.DateOfBirth) %> </div> <div class="editor-field"> <%= Html.EditorFor(model => model.DateOfBirth) %> <%= Html.ValidationMessageFor(model => model.DateOfBirth) %> </div> <p><input type="submit" value="Save" /></p> </fieldset> <% } %> </body> </html>

    Read the article

  • MVC 2 Ajax.Beginform passes returned Html to javascript function

    - by Joe
    Hi, I have a small partial Create Person form in a page above a table of results. I want to be able to post the form to the server, which I can do no problem with ajax.Beginform. <% using (Ajax.BeginForm("Create", new AjaxOptions { OnComplete = "ProcessResponse" })) {%> <fieldset> <legend>Fields</legend> <div class="editor-label"> <%=Html.LabelFor(model => model.FirstName)%> </div> <div class="editor-field"> <%=Html.TextBoxFor(model => model.FirstName)%> <%=Html.ValidationMessageFor(model => model.FirstName)%> </div> <div class="editor-label"> <%=Html.LabelFor(model => model.LastName)%> </div> <div class="editor-field"> <%=Html.TextBoxFor(model => model.LastName)%> <%=Html.ValidationMessageFor(model => model.LastName)%> </div> <p> <input type="submit" /> </p> </fieldset> <% } %> Then in my controller I want to be able to post back a partial which is just a table row if the create is successful and append it to the table, which I can do easily with jquery. $('#personTable tr:last').after(data); However, if server validation fails I want to pass back my partial create person form with the validation errors and replace the existing Create Person form. I have tried returning a Json array Controller: return Json(new { Success = true, Html= this.RenderViewToString("PersonSubform",person) }); Javascript: var json_data = response.get_response().get_object(); with a pass/fail flag and the partial rendered as a string using the solition below but that doesnt render the mvc validation controls when the form fails. SO RenderPartialToString So, is there any way I can hand my javascript the out of the box PartialView("PersonForm") as its returned from my ajax.form? Can I pass some addition info as a Json array so I can tell if its pass or fail and maybe add a message? UPDATE I can now pass the HTML of a PartialView to my javascript but I need to pass some additional data pairs like ServerValidation : true/false and ActionMessage : "you have just created a Person Bill". Ideally I would pass a Json array rather than hidden fields in my partial. function ProcessResponse(response) { var html = response.get_data(); $("#campaignSubform").html(html); } Many thanks in advance

    Read the article

  • integrating tinymce with asp .net MVC 4.0

    - by user1865670
    using ASP .NET MVC 4.0 , VS2012. In one of my page, I tried to integrate a WYSIWYG editor "TinyMCE". To integrate, I followed the following URL : .tugberkugurlu.com My view page is like : @model AboutModels @using FileUploadDemo.Models <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <script src="Scripts/tinymce/jquery.tinymce.js" type="text/javascript"></script> @{ ViewBag.Title = "About"; } @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>About</legend> <div class="editor-label"> @Html.LabelFor(model => model.Title) </div> <div class="editor-field"> @Html.EditorFor(model => model.Title) @Html.ValidationMessageFor(model => model.Title) </div> <div class="editor-label"> @Html.LabelFor(model => model.PostedOn) </div> <div class="editor-field"> @Html.EditorFor(model => model.PostedOn) @Html.ValidationMessageFor(model => model.PostedOn) </div> <div class="editor-label"> @Html.LabelFor(model => model.Tags) </div> <div class="editor-field"> @Html.EditorFor(model => model.Tags) @Html.ValidationMessageFor(model => model.Tags) </div> <div class="editor-label"> @Html.LabelFor(model => model.Content) </div> <div class="editor-field"> @Html.EditorFor(model => model.Content) @Html.ValidationMessageFor(model => model.Content) </div> <p> <input type="submit" value="Create" /> </p> <p> Posted Content : @ViewBag.HtmlContent </p> </fieldset> } Here my Model is like : public class AboutModels { public string Title { get; set; } public DateTime PostedOn { get; set; } public string Tags { get; set; } [UIHint("tinymce_jquery_full"), AllowHtml] public string Content { get; set; } } My about page loads with all features. "@html.EditorFor(model=>model.content)" also loads fine. but no "WYSIWYG" pane(i donno what it is called, the pane is used to edit my text written in the textarea(HTml.editorFor())) is loaded. In the runtime, Exception is thrown in jquery.tinymce.js file. Error Message : `Unhandled exception at line 86, column 11 in http://localhost:1706/Home/About 0x800a01b6 - Microsoft JScript runtime error: Object doesn't support this property or method` And give me two options, Continue or Break . If i continue, the page loads with features as i mentioned earlier. If i Break, then it stays in the jquery.tinymce.js file with a yellow text-background. I have no experience with Javascript/jquery. And new in ASP .NET MVC 4.0, actually this is my first try of web application in .net. I updated jquery from nuGet. What could be the possible ways to solve it?

    Read the article

  • How to Add, Edit and Display one to many relationship entities in ASP.Net MVC 2?

    - by Picflight
    I am looking for best practices conforming to the MVC design pattern. My Entities have the following relationship. tblPortal PortalId PrortalName tblPortalAlias AliasId PortalId HttpAlias Each Portal can have many PortalAlias. I want to Add a New Portal and then Add the associated PortalAlias. I am confused on how I should structure the Views and how I should present the Views to the user. I am looking for some sample code on how to accomplish this. My thoughts are first present the Portal View, let the user add the Portal. Then click the Edit link on the Portal List View and on the Portal Edit View let them Add the PortalAlias. If so, what should the Edit View look like? So far I have: Edit <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<MyProject.Mvc.Models.PortalFormViewModel>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Edit </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Edit</h2> <% Html.RenderPartial("PortalForm", Model); %> <div> <%= Html.ActionLink("Back to List", "Index") %> </div> </asp:Content> PortalForm <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MyProject.Mvc.Models.PortalFormViewModel>" %> <%= Html.ValidationSummary("Please correct the errors and try again.") %> <% using (Html.BeginForm()) {%> <%= Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <div class="editor-label"> <%= Html.LabelFor(model => model.Portal.PortalId) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Portal.PortalId) %> <%= Html.ValidationMessageFor(model => model.Portal.PortalId) %> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.Portal.PortalName) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Portal.PortalName) %> <%= Html.ValidationMessageFor(model => model.Portal.PortalName) %> </div> <p> <input type="submit" value="Save" /> </p> </fieldset> <% } %> Alias<br /><%-- This display is for debug --%> <% foreach (var item in Model.PortalAlias) { %> <%= item.HTTPAlias %><br /> <% } %> PortalFormViewModel public class PortalFormViewModel { public Portal Portal { get; private set; } public IEnumerable<PortalAlias> PortalAlias { get; private set; } public PortalFormViewModel() { Portal = new Portal(); } public PortalFormViewModel(Portal portal) { Portal = portal; PortalAlias = portal.PortalAlias; } }

    Read the article

  • ASP.NET MVC 2 - Saving child entities on form submit

    - by Justin
    Hey, I'm using ASP.NET MVC 2 and am struggling with saving child entities. I have an existing Invoice entity (which I create on a separate form) and then I have a LogHours view that I'd like to use to save InvoiceLog's, which are child entities of Invoice. Here's the view: <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<TothSolutions.Data.Invoice>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Log Hours </asp:Content> <asp:Content ID="Content3" ContentPlaceHolderID="HeadContent" runat="server"> <script type="text/javascript"> $(document).ready(function () { $("#InvoiceLogs_0__Description").focus(); }); </script> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Log Hours</h2> <% using (Html.BeginForm("SaveHours", "Invoices")) {%> <%: Html.ValidationSummary(true) %> <fieldset> <legend>Fields</legend> <table> <tr> <th>Date</th> <th>Description</th> <th>Hours</th> </tr> <% int index = 0; foreach (var log in Model.InvoiceLogs) { %> <tr> <td><%: log.LogDate.ToShortDateString() %></td> <td><%: Html.TextBox("InvoiceLogs[" + index + "].Description")%></td> <td><%: Html.TextBox("InvoiceLogs[" + index + "].Hours")%></td> <td>Hours</td> </tr> <% index++; } %> </table> <p> <%: Html.Hidden("InvoiceID") %> <%: Html.Hidden("CreateDate") %> <input type="submit" value="Save" /> </p> </fieldset> <% } %> <div> <%: Html.ActionLink("Back to List", "Index") %> </div> </asp:Content> And here's the controller code: //GET: /Secure/Invoices/LogHours/ public ActionResult LogHours(int id) { var invoice = DataContext.InvoiceData.Get(id); if (invoice == null) { throw new Exception("Invoice not found with id: " + id); } return View(invoice); } //POST: /Secure/Invoices/SaveHours/ [AcceptVerbs(HttpVerbs.Post)] public ActionResult SaveHours([Bind(Exclude = "InvoiceLogs")]Invoice invoice) { TryUpdateModel(invoice.InvoiceLogs, "InvoiceLogs"); invoice.UpdateDate = DateTime.Now; invoice.DeveloperID = DeveloperID; //attaching existing invoice. DataContext.InvoiceData.Attach(invoice); //save changes. DataContext.SaveChanges(); //redirect to invoice list. return RedirectToAction("Index"); } And the data access code: public static void Attach(Invoice invoice) { var i = new Invoice { InvoiceID = invoice.InvoiceID }; db.Invoices.Attach(i); db.Invoices.ApplyCurrentValues(invoice); } In the SaveHours action, it properly sets the values of the InvoiceLog entities after I call TryUpdateModel but when it does SaveChanges it doesn't update the database with the new values. Also, if you manually update the values of the InvoiceLog entries in the database and then go to this page it doesn't populate the textboxes so it's clearly not binding correctly. Thanks, Justin

    Read the article

  • ASP.NET Membership API not working on Win2008 server/IIS7

    - by Program.X
    I have a very odd problem. I have a web app that uses the .NET Membership API to provide login functionality. This works fine on my local dev machine, using WebDev 4.0 server. I'm using .NET 4.0 with some URL Rewriting, but not on the pages where login is required. I have a Windows Server 2008 with IIS7 However, the Membership API seemingly does not work on the server. I have set up remote debugging and the LoginUser.LoggedIn event of the LoginUser control gets fired okay, but the MembershipUser is null. I get no answer about the username/password being invalid so it seems to be recognising it. If I enter an invalid username/password, I get an invalid username/password response. Some code, if it helps: <asp:ValidationSummary ID="LoginUserValidationSummary" runat="server" CssClass="validation-error-list" ValidationGroup="LoginUserValidationGroup"/> <div class="accountInfo"> <fieldset class="login"> <legend>Account Information</legend> <p> <asp:Label ID="UserNameLabel" runat="server" AssociatedControlID="UserName">Username:</asp:Label> <asp:TextBox ID="UserName" runat="server" CssClass="textEntry"></asp:TextBox> <asp:RequiredFieldValidator ID="UserNameRequired" runat="server" ControlToValidate="UserName" CssClass="validation-error" Display="Dynamic" ErrorMessage="User Name is required." ToolTip="User Name is required." ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator> </p> <p> <asp:Label ID="PasswordLabel" runat="server" AssociatedControlID="Password">Password:</asp:Label> <asp:TextBox ID="Password" runat="server" CssClass="passwordEntry" TextMode="Password"></asp:TextBox> <asp:RequiredFieldValidator ID="PasswordRequired" runat="server" ControlToValidate="Password" CssClass="validation-error" Display="Dynamic" ErrorMessage="Password is required." ToolTip="Password is required." ValidationGroup="LoginUserValidationGroup">*</asp:RequiredFieldValidator> </p> <p> <asp:CheckBox ID="RememberMe" runat="server"/> <asp:Label ID="RememberMeLabel" runat="server" AssociatedControlID="RememberMe" CssClass="inline">Keep me logged in</asp:Label> </p> </fieldset> <p class="login-action"> <asp:Button ID="LoginButton" runat="server" CommandName="Login" CssClass="submitButton" Text="Log In" ValidationGroup="LoginUserValidationGroup"/> </p> and the code behind: protected void Page_Load(object sender, EventArgs e) { LoginUser.LoginError += new EventHandler(LoginUser_LoginError); LoginUser.LoggedIn += new EventHandler(LoginUser_LoggedIn); } void LoginUser_LoggedIn(object sender, EventArgs e) { // this code gets run so it appears logins work Roles.DeleteCookie(); // this behaviour has been removed for testing - no difference } void LoginUser_LoginError(object sender, EventArgs e) { HtmlGenericControl htmlGenericControl = LoginUser.FindControl("errorMessageSpan") as HtmlGenericControl; if (htmlGenericControl != null) htmlGenericControl.Visible = true; } I have "Fiddled" with the Login form reponse and I get the following Cookie-Set headers: Set-Cookie: ASP.NET_SessionId=lpyyiyjw45jjtuav1gdu4jmg; path=/; HttpOnly Set-Cookie: .ASPXAUTH=A7AE08E071DD20872D6BBBAD9167A709DEE55B352283A7F91E1066FFB1529E5C61FCEDC86E558CEA1A837E79640BE88D1F65F14FA8434AA86407DA3AEED575E0649A1AC319752FBCD39B2A4669B0F869; path=/; HttpOnly Set-Cookie: .ASPXROLES=; expires=Mon, 11-Oct-1999 23:00:00 GMT; path=/; HttpOnly I don't know what is useful here because it is obviously encrypted but I find the .APXROLES cookie having no value interesting. It seems to fail to register the cookie, but passes authentication

    Read the article

  • Rails & combo box change event: Help make this obtrusive javascript unobtrusive

    - by DJTripleThreat
    Ok so a friend of mine gave some help with a prototype/obtrusive solution to this but its not quite there. Also, I want to make this unobtrusive instead of using the observe_field function that rails gives me. I don't want to use prototype either because I'm more familiar with JQuery. Here's my problem: I have an Event that can have multiple ServiceTypes and a ServiceType can belong to many Events. A many-to-many relationship between these two exists as an OfferedService. When creating an event, I have a drop down with a list of TimeAllotments that are something like 10 minutes, 12 minutes, 15 minutes, 20 minutes, 30 minutes etc. When the user selects one of these choices, I want a div tag to be filled with a list of ServiceTypes that are associated with this TimeAllotment. So for example, the user selects "10 minutes" and then the div repopulates with services that last 10 minutes. Here is what I have so far: ... some erb code etc and then <fieldset> <legend><%= f.label :time_allotment, "Size of the Appointment Slots:" %></legend> <div> <span class="field-group"> <div> <!-- TimeAllotment is a tabless model which is why this is done like so... --> <%= select("event_service", "time_allotment", TimeAllotment.all.collect {|ta| [ta.title, ta.value]}, {:prompt => true}) %> </div> </span> </div> <div style="clear:both;"></div> Services: <div> <span class="field-group"> <!-- this div right here needs to be repopulated when the above select changes. --> <div id="services"> <% for service_type in ServiceType.all %> <div> <%= check_box_tag "event_service[service_type_ids][]", service_type.id, false %> <%=h service_type.title %> </div> <% end %> </div> </span> </div> <div class="clear"></div> </fieldset> ok so right now ALL of the services are there to be chosen from. I want them to change based on what is selected in the combobox event_service_time_allotment. Can someone help me get pointed in the right direction? I have looked at Ryan's rails casts for using JQuery but its not helpful because he deals with ajax calls for the create action. This would be for the new or edit action. I have a new.js.erb but it doesn't get loaded when calling the new action. I'm super lost as far as getting JQuery to work with my application. I think that if someone can just show me how to make an alert pop up when I change the combo box, and how to return a dataset using ajax the right now, I think I can figure out the rest. Thanks, I know this is super complicated so any helpful answers will get an upvote.

    Read the article

  • Not use CSS definitions for one <FORM>

    - by Svisstack
    I have template from themeforest and i dont want edit css from this template, because i don't have time for it. But i want integrate paypal buttons to my webpage, problem is paypal button use tag for selection payment option. I have overloaded style for tag and this not look like should. How to not use CSS for this element. I dont want use and if i don't must then i dont want edit this CSS;-) This css look wired, i must edit her to solve this problem? What is best solution for this? /*//// - Forms - ////*/ form { margin-bottom:20px; } body.ie7 form, body.ie8 { margin-bottom:40px; } form p { margin-bottom:15px; } form label { float:left; width:140px; margin-top:5px; } form input, form textarea, form select { padding:10px 5px; background:#fff url(../img/bg-input.gif) repeat-x top; border:1px solid #D9D9D9; width:448px; border-radius:3px; -moz-border-radius:3px; -webkit-border-radius:3px; } form input.small { width:35px; } html, body, div, span, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, abbr, address, cite, code, del, dfn, em, img, ins, kbd, q, samp, small, strong, sub, sup, var, b, i, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, figure, footer, header, hgroup, menu, nav, section, menu, time, mark, audio, video { margin:0; padding:0; border:0; outline:0; font-size:100%; vertical-align:baseline; background:transparent; } Can anyone help me?

    Read the article

  • jQuery dynamic field classes not being assigned as desired.

    - by Simon
    Hello, I'm working on a fancy login page with 4 unique states attributed through classes for each field (normal, focus, active-on, active-off). Normal is the default style. Focus is the focus style when nothing is typed. Active-on is the focus style when something has been typed. Active-off is for field that have user text in them, but are not focused right now. Here's a demo to help you understand what I'm doing: http://www.controlstack.com/login My JS is working almost correctly (thanks to some folks on this site), except in 2 cases: If I enter something in the username field, then tab over to the password field, it does not add the ".focus" class to the password field. If I blur out of the username field, then focus back on it, enter a few characters, then delete them, it does not add the ".focus" field. Here's my code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" dir="ltr"> <head> <title>Login</title> <style> input.field {height: 39px; width: 194px; background: url(login-fields.png) no-repeat; overflow: hidden; border: none; outline: none; float: left; margin-right: 7px;} input.field#username {padding: 0 12px;} input.field#username.focus {background-position: 0 -39px;} input.field#username.active-on {background-position: 0 -78px;} input.field#username.active-off {background-position: 0 -117px;} input.field#password {background-position: -218px 0; padding: 0 12px;} input.field#password.focus {background-position: -218px -39px;} input.field#password.active-on {background-position: -218px -78px;} input.field#password.active-off {background-position: -218px -117px;} input.field#go {background-position: -436px 0; width: 88px; margin: 0; cursor: pointer;} </style> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { loginField = $('.field'); firstField = $('.field.first'); firstField.focus(); loginField.focus(function(){ loginVal1 = loginField.val(); if (!loginVal1){ $(this).removeClass('active-off').addClass('focus'); } else { $(this).removeClass('active-off').addClass('active-on'); } }); loginField.live('keydown', function(){ $(this).addClass('active-on').removeClass('active-off'); }).live('keyup', function(){ $(this).toggleClass('active-on', $(this).val() != ''); }) loginField.blur(function(){ loginVal2 = loginField.val(); if (!loginVal2){ $(this).removeClass('focus').removeClass('active-on'); $(this).val(''); } else { $(this).removeClass('focus').removeClass('active-on').addClass('active-off'); } }); }); </script> </head> <body> <h1>Login to your account</h1> <form method="post" action="/"> <fieldset> <input type="text" class="field first focus" id="username" /> <input type="text" class="field" id="password" /> <input type="submit" value="" class="field" id="go" alt="login" title="login" /> </fieldset> </form> </body> </html> Your help is much appreciated!

    Read the article

  • How do you setup an gsp snippet in grails and with spring-security-core?

    - by egervari
    Hi, I have a block of gsp I'd like to reuse and make into a little gsp snippet: <sec:ifLoggedIn> <g:link controller="user" action="showProfile">My Profile</g:link> | <g:link controller="privateMessage" action="list">Inbox</g:link> | <g:link controller="user" action="showPreferences">Preferences</g:link> | <g:link controller="logout" action="index">Logout</g:link> </sec:ifLoggedIn> <sec:ifNotLoggedIn> <form id="loginForm" action="/myproject/j_spring_security_check" method="POST"> <fieldset> <input type='text' name='j_username' id='username' size="15" /> <input type='password' name='j_password' id='password' size="15" /> <input type="submit" value="Login" class="button" /> <a href="#">Register</a> </fieldset> </form> </sec:ifNotLoggedIn> I have learned that I can use g:render template="_loginStuff" to merge the template in with the rest of the markup. However, doing so with Spring Security results in an error: java.lang.NullPointerException at org.codehaus.groovy.grails.plugins.springsecurity.AnnotationFilterInvocationDefinition.determineUrl(AnnotationFilterInvocationDefinition.java:77) at org.codehaus.groovy.grails.plugins.springsecurity.AbstractFilterInvocationDefinition.getAttributes(AbstractFilterInvocationDefinition.java:76) at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:171) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:106) at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:78) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:112) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:188) at org.codehaus.groovy.grails.plugins.springsecurity.RequestHolderAuthenticationFilter.doFilter(RequestHolderAuthenticationFilter.java:40) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.codehaus.groovy.grails.plugins.springsecurity.MutableLogoutFilter.doFilter(MutableLogoutFilter.java:79) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79) at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:355) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:149) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequestFilter.doFilterInternal(GrailsWebRequestFilter.java:67) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.codehaus.groovy.grails.web.filters.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:66) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:849) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:454) at java.lang.Thread.run(Thread.java:619) I have no idea if I am just not using correctly, or if my template needs to be in a special folder... or if Spring-security-core will not allow to be used at all. Help?

    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

  • Post calls RedirectToAction but view specified in RedirectToAction is not rendered

    - by W4IK
    Here's some of the html <form id="frmSubmit" action="/Viewer" style="display:none;"> <div id="renderSubmit" class="renderReport"> <input type="hidden" name="reportYear" id="reportYear" value="" /> <input type="hidden" name="reportMonth" id="reportMonth" value="" /> <input type="hidden" name="propIds" id="propIds" value="" /> <input type="hidden" name="reportName" id="reportName" value="" /> <input type="hidden" name="reportYearFrom" id="reportYearFrom" value="" /> <input type="hidden" name="reportMonthFrom" id="reportMonthFrom" value="" /> <input type="hidden" name="reportYearTo" id="reportYearTo" value="" /> <input type="hidden" name="reportMonthTo" id="reportMonthTo" value="" /> </div> </form> a little further down the page <div id="reportList" class="renderReport"> <fieldset style="width:105%;"> <legend class="reportStepLegend">Step 3. <br /> Click a report name below to view a report</legend> <br /> <% foreach (ReportMetaData item in (ReportMetaDataContainer)ViewData.Model) { %> <div> <input id=<%=item.SSRSName%> type="button" class="reportLink" value="<%=item.DisplayName%>" /> </div> <%}%> </fieldset> </div> Here's the javascript that gets called when the button is clicked $('.reportLink').click(function() { if (CheckDateAndProps() === true) { $('#reportName').val(this.id); var formData = $("#frmSubmit").serializeArray(); $.post('Home/PostViewer/', formData); } }); Note...i did have the $.post like so earlier...but it didn't seem to make any difference $.post('Home/PostViewer/', formData, function(data) { alert(data.Result); }, "json"); Here's the controller code [AcceptVerbs(HttpVerbs.Post)] public ActionResult PostViewer(string reportYear, string reportMonth, string propIds, string reportName, string reportYearFrom, string reportMonthFrom, string reportYearTo, string reportMonthTo) { return RedirectToAction("Viewer"); } All is good in the world up to this point..I'm hitting the above method and all the values are populated. Here's the get ActionResult method [AcceptVerbs(HttpVerbs.Get)] public ActionResult Viewer(string reportYear, string reportMonth, string propIds, string reportName, string reportYearFrom, string reportMonthFrom, string reportYearTo, string reportMonthTo) { return View(); } I'm hitting this too...not seeing any values in the parameters...but that's just because I haven't passed them in yet...I don't think that's whats keeping the Viewer page from displaying.? Now...one would one expect the Viewer view to be rendered...right?...well all I see is the page that this was called from...it never displays the Viewer page???!!?!? Here's the routes from global.asax routes.MapRoute( "Viewer", // Route name "Home/Viewer", // URL with parameters new { controller = "Home", action = "Viewer" } // Parameter defaults ); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = "" } // Parameter defaults ); I can browse directly to the page http://localhost:50083/Home/Viewer and when I do so I hit the get ActionResult method and the page renders just fine. Any help is greatly appreciated!

    Read the article

  • Using label tags in a validation summary error list?

    - by patridge
    I was thinking about making use of <label> tags in my validation error summary on a failed form submit and I can't figure out if it is going to get me in trouble down the line. Can anyone think of a good reason to avoid this approach? Usability, functionality, design, or other issues are all helpful. I really like the idea of clicking a line item in the error list and being jumped to the offending input element, especially in a mobile HTML scenario where vertical orientation is more common and scrolling is a pain. So far the only problem I can find is that labels don't navigate for radio buttons or checkboxes without individual IDs (Clicking a label for a single ID-tagged radio/checkbox element alters its selection). It doesn't make it any worse than no label, though. Here is a stripped down HTML test sample of this idea (CSS omitted for simplicity). <div class="validation-errors"> <p>There was a problem saving your form.</p> <ul> <li><label for="select1">Select 1 is invalid.</label></li> <li><label for="text1">Text 1 is invalid.</label></li> <li><label for="textarea1">TextArea 1 is invalid.</label></li> <li><label for="radio1">Radio 1 is invalid.</label></li> <li><label for="checkbox1">Checkbox 1 is invalid.</label></li> </ul> </div> <form action="/somewhere"> <fieldset><legend>Some Form</legend> <ol> <li><label for="select1">select1</label> <select id="select1" name="select1"> <option value="value1">Value 1</option> <option value="value2">Value 2</option> <option selected="selected" value="value3">Value 3</option> </select></li> <li><label for="text1">text1</label> <input id="text1" name="text1" type="text" value="sometext" /></li> <li><label for="textarea1">textarea1</label> <textarea id="textarea1" name="textarea1" rows="5" cols="25">sometext</textarea></li> <li><ul> <li><label><input type="radio" name="radio1" value="value1" />Value 1</label></li> <li><label><input type="radio" name="radio1" value="value2" checked="checked" />Value 2</label></li> <li><label><input type="radio" name="radio1" value="value3" />Value 3</label></li> </ul></li> <li><ul> <li><label><input type="checkbox" name="checkbox1" value="value1" checked="checked" />Value 1</label></li> <li><label><input type="checkbox" name="checkbox1" value="value2" />Value 2</label></li> <li><label><input type="checkbox" name="checkbox1" value="value3" checked="checked" />Value 3</label></li> </ul></li> <li><input type="submit" value="Save &amp; Continue" /></li> </ol> </fieldset> </form> The only thing I have added to make the click-capable behavior more obvious is to add a CSS rule for the labels. .validation-errors label { text-decoration: underline; cursor: pointer; }

    Read the article

  • Create attribute in XML

    - by user560411
    Hello. I have the following php code that adds data into XML and works correctly. However, in my second step I will create a form that deletes some of the elements. The problem is that I want to add an ID number and then the PHP file will search for it and delete entire node. My question is how can i add an ID into CD for this to work ? For example ( <cd id="xxxx"> ) Also, any ideas or examples of a code that deletes CD having the ID would be appreciate. insert.php ( my index file with the form ) <h1>Playlist</h1> <form action="insert2.php" method="post"> <fieldset> <label for="TITLE">TITLE:</label><input type="text" id="title" name="title" /><br /> <label for="title">BAND:</label> <input type="text" id="band" name="band"/><br /> <label for="path">YEAR:</label> <input type="text" id="year" name="year" /> <br /> <input type="submit" /> </fieldset> </form> <h2>Current entries:</h2> <p>TITLE - BAND - YEAR</p> <?php $doc = new DOMDocument(); $doc->load( 'insert.xml' ); $CATEGORIES = $doc->getElementsByTagName( "CD" ); foreach( $CATEGORIES as $CD ) { $TITLES = $CD->getElementsByTagName( "TITLE" ); $TITLE = $TITLES->item(0)->nodeValue; $BANDS= $CD->getElementsByTagName( "BAND" ); $BAND= $BANDS->item(0)->nodeValue; $YEARS = $CD->getElementsByTagName( "YEAR" ); $YEAR = $YEARS->item(0)->nodeValue; echo "<b>$TITLE - $BAND - $YEAR\n</b><br>"; } ?> inser2.php ( the main code ) <?php $CD = array( 'TITLE' => $_POST['title'], 'BAND' => $_POST['band'], 'YEAR' => $_POST['year'], ); $doc = new DOMDocument(); $doc->load( 'insert.xml' ); $doc->formatOutput = true; $r = $doc->getElementsByTagName("CATEGORIES")->item(0); $b = $doc->createElement("CD"); $TITLE = $doc->createElement("TITLE"); $TITLE->appendChild( $doc->createTextNode( $CD["TITLE"] ) ); $b->appendChild( $TITLE ); $BAND = $doc->createElement("BAND"); $BAND->appendChild( $doc->createTextNode( $CD["BAND"] ) ); $b->appendChild( $BAND ); $YEAR = $doc->createElement("YEAR"); $YEAR->appendChild( $doc->createTextNode( $CD["YEAR"] ) ); $b->appendChild( $YEAR ); $r->appendChild( $b ); $doc->save("insert.xml"); ?> the XML file <?xml version="1.0" encoding="utf-8"?> <MY_CD> <CATEGORIES> <CD> <TITLE>NEVER MIND THE BOLLOCKS</TITLE> <BAND>SEX PISTOLS</BAND> <YEAR>1977</YEAR> </CD> <CD> <TITLE>NEVERMIND</TITLE> <BAND>NIRVANA</BAND> <YEAR>1991</YEAR> </CD> </CATEGORIES> </MY_CD>

    Read the article

  • How to include the login form on the Home index page in MVC

    - by Bernard Larouche
    Hi guys I really need your help for this. I am relatively new to programming and I need help to something that could be easy for a experienced programmer. I would like to get the login form that we get for free in an MVC application on the left sidebar of my Home index page instead of the usual Account/Login page. I am facing some problems. First I need a product object to be displayed on my Home Index page as well. What I did is that I added a product object to the LogOnModel that they provide in the AccountModels class and I created a UserControl (partial view) copying the content of the LogOn.aspx view. Now my Home index.aspx as well as my partial view inherits the LogOnModel class. I can see the Login form on my Home Index page as well as my product object BUT the login Form is never empty. The last username and password always appear there. I know I must have forgotten something or have done something wrong or the way did it is completely wrong !! Please could you give me some advice Thks <%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<CoderForTradersSite.Models.LogOnModel>" %> <h4>Login Form</h4> <p> Please enter your username and password. <%= Html.ActionLink("Register", "Register") %> if you don't have an account. </p> <% using (Html.BeginForm()) { %> <%= Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.") %> <div> <fieldset> <legend>Account Information</legend> <div class="editor-label"> <%= Html.LabelFor(m => m.UserName) %> </div> <div class="editor-field"> <%= Html.TextBoxFor(m => m.UserName) %> <%= Html.ValidationMessageFor(m => m.UserName) %> </div> <div class="editor-label"> <%= Html.LabelFor(m => m.Password) %> </div> <div class="editor-field"> <%= Html.PasswordFor(m => m.Password) %> <%= Html.ValidationMessageFor(m => m.Password) %> </div> <div class="editor-label"> <%= Html.CheckBoxFor(m => m.RememberMe) %> <%= Html.LabelFor(m => m.RememberMe) %> </div> <p> <input type="submit" value="Log On" /> </p> </fieldset> </div> <% } %>

    Read the article

  • test is null in the controller upon post

    - by user281180
    I have the following codes and the test value is always null in the controller after the post. What is wrong with the following code: Model: public class Suitcase { public string Color { get; set; } public string[] Size { get; set; } public List<string> Clothes { get; set; } public List<Test> test { get; set; } } public class Test { public string Name { get; set; } public int ID { get; set; } } The view: <fieldset> <legend>All about my baggage</legend> <div class="editor-label"> <%: Html.LabelFor(model => model.Color) %> </div> <div class="editor-field"> <%: Html.TextBoxFor(model => model.Color) %> </div> <br /> <div class="editor-label"> Width, Height, Depth: </div> <div class="editor-field"> ml.TextBoxFor(model => model.Depth, new { style = "width:50px;" })%> </div> <br /> <div class="editor-label">Suitcase Contents</div> <div class="editor-field"> <div id="clothes-editor"> Clothing Item: <input type="text" id="new-clothes-item" style="width:150px" /> <button id="add-clothes">Add to suitcase</button> </div> <b>Items currently in suitcase:</b> <ul id="clothes-list"> </ul> </div> <p> <button id="pack-it">Put on Baggage Carosel</button> </p> </fieldset> <script type="text/javascript" language="javascript"> $(function () { $("button").button(); // allow users to add items to the suitcase $("#add-clothes").click(function () { var clothesText = $("#new-clothes-item"); $("#clothes-list").append("<li>" + clothesText.val() + "</li>"); clothesText.val("").focus(); }); // pack the suitcase up and send it to the baggage carosel...erm...controller $("#pack-it").click(function () { var clothesList = []; $("#clothes-list li").each(function () { clothesList.push($(this).text()) }); var SizeList = []; SizeList[0] = "Medium"; SizeList[1] = "Large"; SizeList[2] = "small"; var Data = new Object(); Data.test = []; var reading = {}; reading.Name = "Micheal" reading.ID = 123; Data.test[0] = reading; reading.Name = "Rowen" reading.ID = 1234; Data.test[1] = reading; $.ajax({ type: 'POST', traditional: true, data: { Color: $("#Color").val(), Size: SizeList, Clothes: clothesList, test: Data.test } }); }); }); </script> Controller: [HttpPost] public EmptyResult Suitcase(Suitcase lookWhatIPacked) { return new EmptyResult(); }

    Read the article

  • Search Form in Responsive Design - Remove Search button on Mobile

    - by Kevin
    I'm working with a search box in the header of a responsive website. On desktop/tablet widths, there's a search input field and a styled 'search' button to the right. You can type in a search term and either click 'SEARCH' button or just hit enter on the keyboard with the same result. When you scale down to mobile widths, the search input field fills the width of the screen. The submit button falls below it. On a desktop, clicking the button or hitting enter activate the search. On an actual iphone phone, you can hit the 'SEARCH' button, but the native mobile keyboard that rises from the bottom of the screen has a search button where the enter/return key would normally be. It seems to know I'm in a form and the keyboard automatically gives me the option to kick off the search by basically hitting the ENTER key location....but it says SEARCH. So far so good. I figure I don't need the button in the header on mobile since it's already in the keyboard. Therefore, I'll hide the button on mobile widths and everything will be tighter and look better. So I added this to my CSS to hide it in mobile: #search-button {display: none;} But now the search doesn't work at all. On mobile, I don't get the option in the keyboard that showed up before and if I just hit enter, it doesn't work at all. On desktop at mobile width, hitting enter also not longer works. So clearly by hiding the submit/search button, the phone no longer gave me the native option to run the search. In addition, on the desktop at mobile width, even hitting enter inside the search input box also fails to launch the the search. Here's my search box: <form id="search-form" method="get" accept-charset="UTF-8, utf-8" action="search.php"> <fieldset> <div id="search-wrapper"> <label id="search-label" for="search">Item:</label> <input id="search" class="placeholder-color" name="item" type="text" placeholder="Item Number or Description" /> <button id="search-button" title="Go" type="submit"><span class="search-icon"></span></button> </div> </fieldset> </form> Here's what my CSS looks like: #search-wrapper { float: left; display: inline-block; position: relative; white-space: nowrap; } #search-button { display: inline-block; cursor: pointer; vertical-align: top; height: 30px; width: 40px; } @media only screen and (max-width: 639px) { #search-wrapper { display: block; margin-bottom: 7px; } #search-button { /* this didn't work....it hid the button but the search failed to load */ display: none;*/ } } So.....how can I hide this submit button when I'm on a mobile screen, but still let the search run from the mobile keyboard or just run by hitting enter when in the search input box. I was sure that putting display:none on the search button at mobile width would do the trick, but apparently not. Thanks...

    Read the article

  • asp .net MVC 2.0 xval Validation element

    - by ANDyW
    I got one problem with showing error message to element. Is there any option to turn on messages on place where is Html.ValidationMessageFor(model = model.ConfirmPassword). Becsoue for me it isn’t show up. I would like to have summary and near field information too not only red border. Any one know how to do it? using (Ajax.BeginForm("CreateValidForm", "Test", new AjaxOptions { HttpMethod = "Post" })) {%> <div id="validationSummary1"> <%= Html.ValidationSummary(true)%> </div> <fieldset> <legend>Fields</legend> <div class="editor-label"> <%= Html.LabelFor(model => model.Name)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Name)%> <%= Html.ValidationMessageFor(model => model.Name)%> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.Email)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Email)%> <%= Html.ValidationMessageFor(model => model.Email)%> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.Password)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.Password)%> <%= Html.ValidationMessageFor(model => model.Password)%> </div> <div class="editor-label"> <%= Html.LabelFor(model => model.ConfirmPassword)%> </div> <div class="editor-field"> <%= Html.TextBoxFor(model => model.ConfirmPassword)%> <%= Html.ValidationMessageFor(model => model.ConfirmPassword)%> </div> <p> <input type="submit" value="Create" /> </p> </fieldset> <% } %> <%= Html.ClientSideValidation<ValidModel>() .UseValidationSummary("validationSummary1", "Please fix the following problems:") %> Here is link for sample project http://www.sendspace.com/file/m9gl54 .

    Read the article

< Previous Page | 7 8 9 10 11 12 13 14 15 16  | Next Page >