Rectangle 27 11

There is no way to customize the value of the emitted class attribute when using built-in editor templates via the EditorFor method. It hard-codes the class value (more info available here: http://bradwilson.typepad.com/blog/2009/10/aspnet-mvc-2-templates-part-3-default-templates.html)

You have two options:

<%: new HtmlString(Html.EditorFor(m=>m.ConfirmationHeadline).ToString()
        .Replace("class=\"text-box single-line\"", 
                 "class=\"text-box single-line span-11 last\"")) %>
<%: Html.TextBox("ConfirmationHeadline", null, new { @class = "span-11 last" })%>

Does this still work the same in mvc4?

asp.net mvc 2 - Overwriting the class on a `Html.EditorFor` - Stack Ov...

asp.net-mvc-2 textinput class-attributes
Rectangle 27 4

In MCV 5.1 you can take advantage of htmlAttributes. Works like a charm...

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control", placeholder = "Enter your Name" } })

asp.net mvc 2 - Overwriting the class on a `Html.EditorFor` - Stack Ov...

asp.net-mvc-2 textinput class-attributes
Rectangle 27 2

asp.net mvc creates a file called site.css in the content folder. There you can see that the text-box class is set to a width of 30em by default. Reset it to something saner like 15em. The single-line class doesn't appear to be defined anywhere.

asp.net mvc 2 - Overwriting the class on a `Html.EditorFor` - Stack Ov...

asp.net-mvc-2 textinput class-attributes
Rectangle 27 16

I figured this one out with a little help from the web :) The trick is that you have to implement the ISerializable interface in your class that implements IIdentity. I hope this helps save someone else some time :)

[Serializable]
    public class ForumUserIdentity : IIdentity, ISerializable
#region ISerializable Members

        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            if (context.State == StreamingContextStates.CrossAppDomain)
            {
                GenericIdentity gIdent = new GenericIdentity(this.Name, this.AuthenticationType);
                info.SetType(gIdent.GetType());

                System.Reflection.MemberInfo[] serializableMembers;
                object[] serializableValues;

                serializableMembers = FormatterServices.GetSerializableMembers(gIdent.GetType());
                serializableValues = FormatterServices.GetObjectData(gIdent, serializableMembers);

                for (int i = 0; i < serializableMembers.Length; i++)
                {
                    info.AddValue(serializableMembers[i].Name, serializableValues[i]);
                }
            }
            else
            {
                throw new InvalidOperationException("Serialization not supported");
            }
        }

        #endregion

this feature is bs... its been around since 2006 and still affecting me with my asp.net mvc-3 application.

This solved my problem. The same thing goes for IPrincipal as well.

why are you created a new GenericIdentity instead of a CustomIdentity in your DeSerialization code? => `GenericIdentity gIdent = new GenericIdentity(...)' ??

System.ISerializable
System.Runtime.Serialization.ISerializable

asp.net mvc 2 - Implementing a Custom Identity and IPrincipal in MVC -...

asp.net-mvc-2 iprincipal iidentity
Rectangle 27 162

Adding a class to Html.EditorFor doesn't make sense as inside its template you could have many different tags. So you need to assign the class inside the editor template:

@Html.EditorFor(x => x.Created)

and in the custom template:

<div>
    @Html.TextBoxForModel(x => x.Created, new { @class = "date" })
</div>

This works great, thanks. Having trouble formatting the field value per the DisplayFormat annotation in my model. Formatted as annotated with EditorFor and DisplayFor, but not TextBoxFor :( Looks like I must use a custom template, unless someone can point me to something I'm missing. ?

Having the same problem where TextBoxFor doesn't honor the DisplayFormat set.

This is GroundController to ModelTom, i'm sending you the View and i'm floating in the most MVC way.

i have same issue, but i can't use TextBoxFor as i need DisplayFormat, which works with Editor or Display, but at the same time i need class too, so that i can display text in readonly form

ASP.NET MVC 3 Razor - Adding class to EditorFor - Stack Overflow

asp.net-mvc asp.net-mvc-3 razor
Rectangle 27 158

Adding a class to Html.EditorFor doesn't make sense as inside its template you could have many different tags. So you need to assign the class inside the editor template:

@Html.EditorFor(x => x.Created)

and in the custom template:

<div>
    @Html.TextBoxForModel(x => x.Created, new { @class = "date" })
</div>

This works great, thanks. Having trouble formatting the field value per the DisplayFormat annotation in my model. Formatted as annotated with EditorFor and DisplayFor, but not TextBoxFor :( Looks like I must use a custom template, unless someone can point me to something I'm missing. ?

Having the same problem where TextBoxFor doesn't honor the DisplayFormat set.

This is GroundController to ModelTom, i'm sending you the View and i'm floating in the most MVC way.

i have same issue, but i can't use TextBoxFor as i need DisplayFormat, which works with Editor or Display, but at the same time i need class too, so that i can display text in readonly form

ASP.NET MVC 3 Razor - Adding class to EditorFor - Stack Overflow

asp.net-mvc asp.net-mvc-3 razor
Rectangle 27 2

Do you know the ViewModel approuch? It is a class that represents what a View need to show. You could create a ViewModel class with theses proeprties you need and type your Views with this class, fill it with NHibernate and then show it, for sample:

public class ApplicationTypeMasterViewModel
{
   public int Id { get; set; }
   pubic string Name { get; set; }
   pubic string CityName { get; set; }
   pubic string StateName { get; set; }

   // other properties you need

   public ApplicationTypeMasterViewModel() { }   
}

in your Service Layer, try something like this:

public ApplicationTypeMasterViewModel GetByID(int ID)
    {
        using (ISession session = NHibernateHelper.OpenSession())
        {
            return session.Query<ApplicationTypeMaster>()
                                                    .Fetch(x => x.City).ThenFetch(c => c.State)
                            .Where(x => x.Id == ID)
                            .Select(x => new ApplicationTypeMasterViewModel() { 
                                                    Id = x.Id, 
                                                    Name = x.Name, 
                                                    CityName = x.City.Name, 
                                                    StateName = x.City.State.Name
                                                    // other properties you need
                                            })
                            .FirstOrDefault();
        } 
    }

You could do it using Lists or Single objects.

In the controller you call this method and pass the ViewModel to your View and render it:

<p>
    <label>Name: </labe>
    <%: Model.Name %>
</p>

<p>
    <label>City: </labe>
    <%: Model.CityName %>
</p>


<p>
    <label>State: </labe>
    <%: Model.StateName %>
</p>

Yes I am aware of the ViewModel approach. However, I did not implement it because it would have bought an additional layer to the current implementation. The crux of the problem is when I try to list 100 records which has 5 such views. It's taking 25 seconds just to list them. I suspect it is because of continous database calls everytime it tries to get the description. To improve this I loaded all the master values to a ICollection and query the collection when I do a list. The load time has now come to 20 seconds. Not sure how I can improve its performance anymore.

Maybe it's executing by lazyLoading, you could try using EargLoading using Fetch, FetchMany extension methods for Nhibernate To Linq and use it to execute a single query on database. See my edits

HOW TO Implentation on NHibernate with ASP.NET MVC 2 - Stack Overflow

asp.net-mvc nhibernate asp.net-mvc-2
Rectangle 27 5

The request validation feature in ASP.NET provides a certain level of default protection against cross-site scripting (XSS) attacks. In previous versions of ASP.NET, request validation was enabled by default. However, it applied only to ASP.NET pages (.aspx files and their class files) and only when those pages were executing.

In ASP.NET 4, by default, request validation is enabled for all requests, because it is enabled before the BeginRequest phase of an HTTP request. As a result, request validation applies to requests for all ASP.NET resources, not just .aspx page requests. This includes requests such as Web service calls and custom HTTP handlers. Request validation is also active when custom HTTP modules are reading the contents of an HTTP request.

As a result, request validation errors might now occur for requests that previously did not trigger errors. To revert to the behavior of the ASP.NET 2.0 request validation feature, add the following setting in the Web.config file:

<httpRuntime requestValidationMode="2.0" />

However, we recommend that you analyze any request validation errors to determine whether existing handlers, modules, or other custom code accesses potentially unsafe HTTP inputs that could be XSS attack vectors.

asp.net mvc 2 - a potentially dangerous request.form value was detecte...

asp.net-mvc-2
Rectangle 27 2

Are you overriding the FormatErrorMessage() method in your class?

public override string FormatErrorMessage(string name)
{
   return String.Format(CultureInfo.CurrentUICulture, ErrorMessageString,
                        OriginalProperty, ConfirmProperty);
}

FYI, paste code in with a leading four space buffer on the left and it will be formatted just fine (at least sufficient for our purposes).

asp.net mvc 2 - ASP MVC 2 Custom CLASS Validation Attribute error mess...

asp.net-mvc-2 validation
Rectangle 27 2

i see this question because i have the same problem, and the solution of Andrew is good but no solve the problem of the user385060, because the problem is not the space, is the execution stack, if you use a dataanotations validations, the validations of fields execute first and if no errors found, execute validation of class level. I hope this answer help some others people.

asp.net mvc 2 - ASP MVC 2 Custom CLASS Validation Attribute error mess...

asp.net-mvc-2 validation
Rectangle 27 165

In the MVC project template in VS2013 Update 2, there should be a file called App_Start/IdentityConfig.cs. In it you should find the class ApplicationUserManager and a static factory method called Create(). That's where the user manager class is configured, including the server-side validation rules for passwords are defined. For example:

manager.PasswordValidator = new PasswordValidator
{
    RequiredLength = 6,
    RequireNonLetterOrDigit = true,
    RequireDigit = true,
    RequireLowercase = true,
    RequireUppercase = true,
};

One thing to note, the default rules you listed will result in an error for the password Test123 with the message "Passwords must have at least one non letter or digit character." which is very deceiving because it seems that if both RequireNonLetterOrDigit and RequireDigit are true that RequireDigit steals the numeric text and forces the password validation to fail, then tells the user to do something they already did.

RequireNonLetterOrDigit = the password requires a character that is not a letter and not a digit.

How do you override the error text that is returned?

In the new ASP.NET 5, corresponding method couldn't be found. Can you suggest any other way that will work in that?

How To Change Password Validation in ASP.Net MVC Identity 2? - Stack O...

asp.net-mvc asp.net-identity asp.net-identity-2
Rectangle 27 1

If both Ynum and Level are int you first have to verify that the class Test looks like this:

public class Test
{
    public int Tnum { get; set; }
    public int Level {get;set;}
}

And then the query should look something like this:

public IList<Test> GetData(int IDCus)
{
    var list = (
                from j in Context.Test
                join y in this.Context.Test1 
                    on j.ID equals y.ID
                where 
                    j.ID == IDCus
                select new Test()
                    {
                        Tnum = j.Ynum,
                        Level = y.Level
                    }
            );
    return list.ToList();
}

If you are using Test somewhere else you might have to create a new class for this call, we can call it Test2. Then the class should look like this:

public class Test2
{
    public int Tnum { get; set; }
    public int Level {get;set;}
}

And the function for getting the information should look like this:

public IList<Test2> GetData(int IDCus)
{
    var list = (
                from j in Context.Test
                join y in this.Context.Test1 
                    on j.ID equals y.ID
                where 
                    j.ID == IDCus
                select new Test2()
                    {
                        Tnum = j.Ynum,
                        Level = y.Level
                    }
            );
    return list.ToList();
}

asp.net mvc 2 - Cannot implicitly convert type of dynamic linq-to-sql ...

linq-to-sql asp.net-mvc-2
Rectangle 27 1

Create a class that wraps both objects up into one. Then return your wrapper object.

public class Wrapper
{
   List<Filter> Filters { get; set; }
   List<Deal> Deals { get; set; }
}

Okay, but I have a ViewModel... the issue is returning both filters and deals INTO the ViewModel.

c# - ASP.NET MVC 2: Return Multiple Objects? - Stack Overflow

c# asp.net-mvc-2
Rectangle 27 1

You should be able to tell which fields have validation errors by checking if the associated textbox has a input-validation-error class already applied to it, or checking the error message span exists and has a class of field-validation-error.

Another idea is to create your own custom ValidationMessageFor which outputs the html with the div you need with the appropriate class applied.

Yep -- I'm digging the idea of a custom HTML helper.

ASP.NET MVC 2 validation: Easy way to add CSS class to element on erro...

asp.net css validation asp.net-mvc-2
Rectangle 27 3

Please see the following posts, this question has been asked before on Stackoverflow.

Google

asp.net mvc - How to add custom data attributes and classes to `@Html....

asp.net-mvc asp.net-mvc-4 html-helper razor-2
Rectangle 27 3

It works when I apply @Html.EditorFor, but I need control over the class attribute. What am I doing wrong?

Nothing, it's how things work. Only the EditorFor and DisplayFor helpers respect the [DisplayFormat] attribute.

I understand that you are using TextBoxFor because you want to apply a custom class to the field which is what the EditorFor doesn't allow you to. But that's not true. All that the EditorFor helper does is to render the corresponding editor template. And if you do not have a custom template it renders the default one.

Well, you write a custom editor template for the DateTime type that will behave as you want. Just like that in ~/Views/Shared/EditorTemplates/DateTime.cshtml:

@Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, ViewData)
@Html.EditorFor(model => model.ScreeningDate, new { @class="date maintainState" })
  • We applied the desired format
  • We applied the desired class to the input field

And if you wanna kill a third rabbit and be able to validate this custom format when the form is submitted back (because remember that the default model binder doesn't care much about this [DisplayFormat] attribute) you could write a custom model binder that will respect the [DisplayFormat] attribute, just as I explained here: https://stackoverflow.com/a/7836093/29407

asp.net mvc 4 - MVC view displaying time when date only required - Sta...

asp.net-mvc-4
Rectangle 27 1

You could use a class attribute to achieve this:

[AttributeUsage(AttributeTargets.Class)]
public class RatingValidation : ValidationAttribute
{
    public override bool IsValid(object value)
    {
        var model = (MyModel)value;
        // TODO: here you have the model so work with the 
        // Rating and Heading properties to perform your 
        // validation logic

        return true;
    }
}
[RatingValidation]
public class MyModel
{
    public String Heading { get; set; }
    public int Rating { get; set; }
}

I initially started with this approach. It has 2 problems. First of all, it seems like only 1 validation error can be displayed at a time. An example would be, say Rating's value wasn't b/t 1 and 5, but the user didn't put a value for some other required property in the model. I could check both here, but only display a single message. Furthermore, handling the actual displaying of that message inside the custom control finicky. I can post code to illustrate what I mean.

@Jason, yes this allows a single validation message to be displayed but for the combined property validation. You can still place validation attributes on individual properties like [Required] to validate each property separately. You can also have multiple class validation attributes which will allow you to validate different combinations of dependent properties with different error messages. FluentValidation is still worth checking out though.

@Darin, so to dig a bit deeper here...internally, do the DataAnnotations kick into place during the model binding process? I suppose that would be where the ModelState & Errors are added. Is that correct? I'm thinking I'm going to be stuck creating a custom ModelBinder here like @Jfar suggested.

Yes, validation kicks in during model binding. I'm thinking I'm going to be stuck creating a custom ModelBinder : hell no, if you had to write a custom model binder every time you needed to validate two dependent properties on a view model, ASP.NET MVC usefulness would be extremely limited to some Hello World applications which of course is not the case. I cannot even imagine writing a complex application with many business rules (and I have written some). Btw, did you have a look at FluentValidation (maybe the third time I am asking)?

@Darin Dimitrov - You know it takes just the very small amount of code to create a custom model binder right? Throw in a little infrastructure ( lostechies.com/blogs/jimmy_bogard/archive/2009/03/17/ ) and your writing the same amount of code per model binder as you would with FluentVal.

c# - How do I access other attribute values from inside a custom Valid...

c# asp.net-mvc validation asp.net-mvc-2
Rectangle 27 3

You're better off using the TextBoxFor method as it allows you to change the id and class of the element directly whereas EditorFor doesn't unless you create a custom edit state for it (using EditorTemplate).

@Html.TextBoxFor(model => model.ID, new { id = "ID" })

I believe @Html.EditorFor(model => model.ID) will set the name attribute as that is what mvc depends upon to do its model binding so if the above is not to your liking you can perhaps use the name as a selector.

how to set value of @Html.EditorFor using jquery in in asp.net mvc - S...

asp.net-mvc asp.net-mvc-4
Rectangle 27 3

//C# class

public class DashBoardViewModel 
{
    public int Id { get; set;} 
    public decimal TotalSales { get; set;} 
    public string Url { get; set;} 
     public string MyDate{ get; set;} 
}

//JavaScript file
//Create dashboard.js file
$(document).ready(function () {

    // See the html on the View below
    $('.dashboardUrl').on('click', function(){
        var url = $(this).attr("href"); 
    });

    $("#inpDateCompleted").change(function () {   

        // Construct your view model to send to the controller
        // Pass viewModel to ajax function 

        // Date
        var myDate = $('.myDate').val();

        // IF YOU USE @Html.EditorFor(), the myDate is as below
        var myDate = $('#MyDate').val();
        var viewModel = { Id : 1, TotalSales: 50, Url: url, MyDate: myDate };


        $.ajax({
            type: 'GET',
            dataType: 'json',
            cache: false,
            url: '/Dashboard/IndexPartial',
            data: viewModel ,
            success: function (data, textStatus, jqXHR) {
                //Do Stuff 
                $("#DailyInvoiceItems").html(data.Id);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //Do Stuff or Nothing
            }
        });

    });
});

//ASP.NET 5 MVC 6 Controller
public class DashboardController {

    [HttpGet]
    public IActionResult IndexPartial(DashBoardViewModel viewModel )
    {
        // Do stuff with my model
        var model = new DashBoardViewModel {  Id = 23 /* Some more results here*/ };
        return Json(model);
    }
}

// MVC View 
// Include jQuerylibrary
// Include dashboard.js 
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/dashboard.js"></script>
// If you want to capture your URL dynamically 

<div>
    <a class="dashboardUrl" href ="@Url.Action("IndexPartial","Dashboard")"> LinkText </a>
</div>
<div>
    <input class="myDate" type="text"/>
//OR
   @Html.EditorFor(model => model.MyDate) 
</div>

Thanks, using 'var viewModel = { Id : 1, MyDate:};' how do I get a value from a textbox on the page into the mydate parameter?

Sorry I was meaning how do I get a date from a textbox into the viewModel parameter?

Great, and sorry - once last question, how do I get the results of the ajax query to load in the "#DailyInvoiceItems" DIV?

asp.net mvc - Pass Model To Controller using Jquery/Ajax - Stack Overf...

asp.net-mvc asp.net-core asp.net-core-mvc
Rectangle 27 1

The options for class wide custom validation attributes are pretty poor right now without any really good extensibility points. Your pretty much stuck creating a custom ModelBinder, which can then add values to ModelState, to do anything complex with validation attributes.

Use the attributes just like you would and then detect what Types are requested from the binder, Reflect to find the attributes, and then validated/add to model state as necessary.

MVC 3 fixes this problem but until then your stuck creating your own binder.

This is unrealistic. I understand you're point: that the validation extensibility in MVC 2 is lagging in maturity behind MVC itself; however, MVC 3 is .Net 4.0 only and uses a ton of new conventions as far as syntax goes. There's not much of a business case on redoing this project in MVC 3 when it's not even out yet and the benefits are minimal considering this project is very close to production release. Still, I appreciate your comment. Thank you for taking the time to give your feedback.

@Jason? Well check out, lostechies.com/blogs/jimmy_bogard/archive/2009/03/17/, and then see if that changes your mind. The attributes are nice but there are other ways to accomplish your goal. I know "wait" isn't a practical answer but its the only one which correctly answers what your looking for.

-1 for doing validation in a model binder. IMHO validation is an aspect of the application that should be independent. Suggesting to use reflection and adding manually to the model state means that your validation logic is tied to the MVC infrastructure and not reusable. Also you risk up having parts of the validation in the model binder and other parts as data annotation attributes, etc... which is not very maintainable solution. Also in the example you showed, no validation is performed, it also states in the first paragraph the role of a model binder. No validation there.

@Darin Dimitrov, lol, you know MVC does ModelValidation in the model binder? In fact this is considered a feature. "Downvoted for using the same technique the framework uses". - "IMHO validation is an aspect of the application that should be independent" thats a bad answer. Validating the user entered a int into a textbox is not part of independent business logic but directly tied to the underlying UI platform.

I upvoted jfar's response b/c I think his explanation holds pretty well. I agree with trying to separate the concerns and really would rather not mix my validation logic with a custom model binder, but after doing a test app, I know I can at least get all of the properties of an object in the BindModel method (and the SetProperty method provided I add logic to ensure both properties have been validated).

c# - How do I access other attribute values from inside a custom Valid...

c# asp.net-mvc validation asp.net-mvc-2