MVC :: Access Model Validation Inside Custom Model Binder?

Sep 1, 2010

Is it possible, inside a Custom Model Binder, to fire "something" that "says" the value is invalid so it gets handled by validation part?

Basically, I am getting an exception when the value for the property is invalid.

View 1 Replies


Similar Messages:

Default Model Binder Does Not Bind Model Class

Dec 28, 2010

I am trying to make a post that should use the Default Model Binder functionality in ASP.NET MVC 2 but unfortunately I can't get through. When I click on the checkout button I populate a form dinamically using jQuery code and then submit this form to the server. This is the form that get submitted

<form action="/x/Order/Checkout" id="cartForm" method="post">
<input name="__RequestVerificationToken" type="hidden" value="UDjN9RdWheKyWK5Q71MvXAbbDNel6buJd5Pamp/jx39InuyYIQVptcEubIA2W8DMUzWwnZjSGkLspkmDPbsIxy8EVuLvfCSZJJnl/NrooreouptwM/PaBEz2v6ZjO3I26IKRGZPqLxGGfITYqlf8Ow==">
<input id="CustomerID" name="CustomerID" type="hidden" value="1">
<input id="FirmID" name="FirmID" type="hidden" value="2">
<input type="hidden" name="CartItems[0].ServiceTypeID" value="1">
<input type="hidden" name="CartItems[0].Quantity" value="1">
<input type="hidden" name="CartItems[1].ServiceTypeID" value="2">
<input type="hidden" name="CartItems[1].Quantity" value="1">
</form>

This is the jQuery code that handle the submit event for the form
$("#cartForm").submit(function (event) {
event.preventDefault(); var form = $("#cartForm");
var panel = form.parent(); panel.parent().block();
$.ajax({ type: "post", dataType: "html",
url: '<%: Url.Content("~/Order/Checkout") %>',
async: false, data: form.serialize(),
success: function (response, status, xml) { panel.parent().unblock(); },
error: function (response) { panel.parent().unblock(); } }); });

This is the controller action that should be get called
[HttpPost]
[ValidateAntiForgeryToken]
public virtual ActionResult Checkout( CartModel cart ) {
} And finally this is the CartModel class involved
public class CartModel : BaseModel{
public int CustomerID { get; set; }
public int FirmID { get; set; }
public List<CartItemModel> CartItems { get; set; }
public CartModel() { CartItems = new List<CartItemModel>();
} } public class CartItemModel : BaseModel
{ public int ServiceTypeID { get; set; }
public int Quantity { get; set; } }

But the default Model Binder does not bind the web form data to a CartModel class. Using Fiddler I have been able to see that the data sent to the server is correct as you can see from the following snapshot.

View 1 Replies

Custom Model Binder For DropDownList Not Selecting Correct Value?

Sep 4, 2010

i've created my own custom model binder to handle a Section DropDownList defined in my view as:

Html.DropDownListFor(m => m.Category.Section, new SelectList(Model.Sections, "SectionID", "SectionName"), "-- Please Select --")

And here is my model binder:

public class SectionModelBinder : DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (bindingContext.ModelType.IsAssignableFrom(typeof(Section)) && value != null)
{
if (Utilities.IsInteger(value.AttemptedValue))
return Section.GetById(Convert.ToInt32(value.AttemptedValue));
else if (value.AttemptedValue == "")
return null;
}
return base.BindModel(controllerContext, bindingContext);
}
}

Now within my controller i can say:

[HttpPost]
public ActionResult Create(FormCollection collection)
{
var category = new Category();
if (!TryUpdateModel(category, "Category")
return View(new CategoryForm(category, _sectionRepository().GetAll()));
}

This validates nicely and the correct value for the section is assigned when the model is updated, however it does not select the correct value if another property doesn't validate.

View 1 Replies

Custom Model Binder Option In MVC 2 RC - How To Iterate Over Form Values

Feb 2, 2010

I'm using the MVC 2 RC. I have a custom model binder that used to iterate over posted form values in MVC 1.0 like this:

[Code]....

View 2 Replies

MVC :: Access Custom Model Inside ViewUserControl?

Nov 28, 2010

I want to pass custom param to my ViewUserControl using custom Model.

1. I have created model

[Code]....

2. I have created custom ViewUserControl

[Code]....

3. I am rendering my custom ViewUserControl and passing new Model

[Code]....

The problem is that I don't know how to get acces to my model instance inside my custom ViewUserControl

View 2 Replies

MVC :: Indicate To The Model Binder That Want To Update The List

Apr 17, 2010

I have a control that's bound to a list property. If I remove elements from that list using javascript and post, then the model gets updated, and the elements get removed.

Unless I remove all the items from the list. Then no names for that property go into the form data, and so the default model binder leaves the model's list untouched. This code from DefaultModelBinder.cs line 572 in the RTM sources makes it clear:

[Code]....

So how do I indicate to the model binder that I do want it to update the list and Ido want the list to be emptied?

View 3 Replies

MVC Model Binder Not Working With A Dictionary?

Apr 4, 2011

Given the following view model and action using the DefaultModelBinder, it seems to ignore the dictionary, but bind all other properties correctly. Am I missing something here? Looking at the MVC source code this seems legit.

public class SomeViewModel
{
public SomeViewModel()
{[code].....

View 1 Replies

MVC :: Model Binder To Collection Properties?

Jul 14, 2010

I need to bind a bunch of properties over my model entities. All of them uses the List<T> class. I already managed to write a model binder that can treat individualy types derived from that class, but i can't set the value of this property on the model. every time i check the model afer the bind process i see a list with 0 itens.

Here's how it runs.

After i post the values the model binder catchs up the types for bindingAt the custom model binder i check if this property is a List<T> typeIf it is then i perform the bind like it have to be, if not i let the default binder do the job.Finally i return the object binded. What happens next is the issue i've mentioned "i see a list with 0 itens" on the Model property.

Here is the code of Custom Model Binder:

[Code]....

View 1 Replies

MVC :: Custom Model Validation Against Collection Of Instances?

Jul 22, 2010

i am creating a MVC2 application for pubs and bars. I have a model 'Opening_Time' with the following properties:

int Day,time OpeningTimetime ClosingTimeWhen adding/editing an Opening_Time, I want to validate an Opening_Time, to check the user isn't adding one for an existing Day (ie they can't have two entries for the same day).

How/Where is the best place to do this?

Preferably, I want to do it a Model level, so I can use Model.IsValid and the Html.Form helpers

View 3 Replies

MVC Default Model Binder - Bind A Multiselect Dropdown To An IList

Sep 13, 2010

I'm using MVC 2.0 in an ASP.NET application using NHibernate. I have a working View, Controller and data access layer using NHibernate that is able to display and save an entity with a relationship to another mapped entity: Person -- > Location It's using the HTML helper HTML.DropDownListFor() to display a list of all Locations. The user is able to select one of the Locations from the list, and press save. The default model binder correctly sets the value of the Location on the Person entity being saved. This location is an nhibernate mapped entity, and is instantiated and has the id value that was selected in the dropdown list. Obviously, since the dropdown list that holds locations only has the ids of the locations, the rest of the values for the location are null. This is OK. I am only trying to save the Person with a reference to an existing location.

So, here comes the complication. We have a need to change the relationship between the two entities. Now the Person can have a reference to many locations. Person.Locations will be an IList My question is, how do you get the default model binder to take selections from a multiselect dropdown and populate an IList. I've managed to save collections of entities in the past using the syntax [index].PropertyName as explaing by Phil Haacked .... [URL]

The issue here is that I have only a dropdown list, and it will post back to the modelbinder a repeating key with different values:

Person.Location.Id: 2
Person.Location.Id: 4
Person.Location.Id: 5

This, unfortunately, doesn't work. the Location list keeps coming back Null. Our UI guy is using a slick JQuery pluggin to display the items in the select list, so I'd rather not have to use a different UI.

View 1 Replies

MVC :: Binding Class On Action Method Using Default Model Binder

Nov 7, 2010

I saw a post with posibble problems with Model Binding which is mentioned here. [URL]. Whats the best approach to this? Different approaches are below.
[Code]....

View 2 Replies

Binding Multiple Forms To Single Model Using Default Binder?

Jun 10, 2010

I have a complex page with several forms on it. The page is divided into sections, and each section has a continue button on it. The page is bound to a pageViewModel, each section addresses a different set of properties on the model. The continue button makes an ajax call to the controller, and the model binder binds it appropriately to the appropriate sections of the model. The section is refreshed appropriately. Finally, I would like to have a save button at the bottom of the page that takes all the forms, and binds all of the forms to the model. The model, at this point has all of the properties filled out, and can be processed accordingly. Can I accomplish this by some ASP MVC magic?

View 2 Replies

MVC :: Validation Of Model In Side Model

Oct 12, 2010

I have recently started working on ASP.NET with MVC 2 framework, and I am facing following difficulty in validating my data,

Scenario:

In my application the view (ASPX) is divided into tabs (jQuery) and each tab's content is ViewUserControl (ASCX). The main model for the view has collection of sub models for individual tabs. I use RenderPartial method to render view user control.

[Code]....

And the user control (Tab1.ascx) refers the specific model for it,

[Code]....

Now if in my Tab1Model if I put following validation

[Code]....

In the controller ModelState.IsValid is always indicates TRUE. How do I override the validation behavior such that it as well looks the items in the collection member (which holds sub models) as well.

<%= Html.ValidationMessage("FirstName") %>

View 1 Replies

MVC :: How To Display Model Level Custom Data Annotation Validation Error

Nov 30, 2010

I am a MVC newbie & am lost in various ways validation can be implemented in my application.

I created a custom model-level data annotation validator attribute, but am unable to display its error message in the view. Basically, I have let's say 5 properties in the Entity class Job (model-level custom attribute called UniqueKeywords defined on it):

1) LoginID: value comes in the URL

2) Title: Required property level attribute defined on it

3) CatID1, CatID2, CatID3 - 3 categoryIDs - these are dropdowns in the view with same list of keywords in all 3.

I want to mandate that the values picked by the user in all 3 category dropdowns should be different.

With reference to the code pasted below, here is the explanation of what happens:

When I submit the form without specifying a title or picking anything from any of the 3 category dropdowns, the validation occurs for the property level Required attribute as well as model level uniquekeywords attribute, but the error is displayed only next to the required field "Title". I can confirm that the custom validation also works by filling in some text in the Title field & then re-posting the form...this re-displays the view, but the error message "Category cannot be duplicated" is not displayed.

Only relevant code sections are pasted below:

My Entity class code:

[Code]....

View 10 Replies

ADO.NET :: Write Custom Functionality To Access The Model (POCO) Metadata

Dec 7, 2010

I was wondering if anyone can point me in the right direction? I have a POCO model and I am using Code First CTP. In my application, I set the database to be recreated whenever the model changes.

I would like to write custom functionality to access the model (POCO) metadata same way as EF sees it and use that to generate some source files (using T4). I would like to access the processed model not having to worry about finding properties that hold primary keys or any other conventions (implicit or not). What is the way to go about it?

View 2 Replies

C# - How To Access Attributes Of Properties In The Model From Strongly Typed Custom HtmlHelper

Mar 18, 2011

I have a view that is strongly typed and its model is of type LogOnModel. That LogOnModel has anotated properties like this one:

[Required(ErrorMessage = "Please enter your password")]
[DataType(DataType.Password)]
[Display(Name = "Password", Description = "Your secreet password")]
public string Password { get; set; }

All of them has Display anotation with Display.Descripion property set. I want to create HtmlHelper extension method that will output <span> containg the value of Display.Description property. So for example if I called my extension method DescriptionFor than this code:

<%: Html.DescriptionFor(m => m.Password) %>

should produce following html: <span>Your secreet password</span>

View 1 Replies

MVC :: Store Model In Separate Class Library- Pass Model Objects?

May 19, 2010

I'm building an MVC 2 RTM app, and I want to be able to share my model across applications. I'd *like* to be able to implement it like:ASP.NET MVC2 app (holds Views and Controllers)Class library to hold Model(s)WCF app to handle the data transactions with the models via different data stores across apps I had the MVC app working fine, but I wanted to abstract the data stuff and be able to work with the model across apps through the WCF site, so I created a class library project and moved all of the Models classes into that and set-up a WCF app, then added project references to the MVC and WCF apps that point at the class library. The idea was I can create services that take and return objects from the model via method calls across apps. It appears that everything's wired up correctly in the MVC project, so I'm passing the objects stored in the Models class library between controllers and views and everythig is compiling just fine, but for some reason the data is not being passed back from the views to the controller on POST -- all of the properties in the classes are null or empty.

When I debug the app, I can see that the values are stored in the model data dictionary but not the model object itself. What am I doing wrong? Am I on the wrong path, or missing something obvious (to some)?

View 2 Replies

ADO.NET :: Entity Model - Update Model From DB And The Assembly Reference Seems To Be Missing?

Jan 10, 2011

I made a few changes to the DB in SQL server management studio then right clicked on the .edmx doc to get it to update. That seemed to work fine but when i compiled the app everything that referenced the EF seems to be broken.The Error list now contains the below error for all classes that used it.

The type or namespace name '' could not be found (are you missing a using directive or an assembly reference?)

View 4 Replies

HttpHandlers / Modules :: Process Model Or Thread Model Of A Website?

Mar 11, 2010

I have an issue of static variable in an asp.net application. Let's say I have a server with 8 CPUs running windows 2008 R2 hosting an asp.net webbsite, nothing fancy here, no funny configuration.

Is the following statement true? at any single time, there's one and only one process is running and accepting requests, even in the recycling stage. The reason I am asking is: I have a static field in my class, and I want to make that's the only static instance in the website. I've heard in some circumstances, IIS is recylcing your application, and it will start a new process, but the old process is still working, thus I will have 2 static instances in memory, which defeat the purpose of static field.

One step further, let's assume there might be 2 instances in memory, can I assume there are at most 2 instances at any single time? And can I assume once the second instance is up, the first instance will NEVER accept new requests?

Another question: Recently I have a problem with an applicationdomain concept. Looks like if an application domain causes a memory leak, unload the domain will not release the memory (Umanaged leak). So to what extent Application Domain is isolated?

View 1 Replies

How To Bind Form Collection Back To Custom Model Object That Uses 2 Custom Objects

Mar 23, 2010

What I'm trying to do is rather basic, but I might have my facts mixed up. I have a details page that has a custom class as it's Model. The custom class uses 2 custom objects with yet another custom object a property of one of the 2. The details page outputs a fair amount of information, but allows the user to post a comment. When the user clicks the post button, the page gets posted to a Details action that looks something like this:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Details(VideoDetailModel vidAndComment) { ....}
[Code]....

The only fields on the form that is posted are CommentText and VideoId. Here is what the VideoDetailModel looks like.

public class VideoDetailModel
{
public VideoDetailModel()
{
[Code]....
I suppose if I added more form fields for the properties I need, they would get posted, but I only need 1 form entry field for the CommentText. If I could get the same Model objects value that were sent to the page to post with the page, it looks like the solution is rather simple. I think using the RenderPartial in the middle of a form is problematic somehow to how the form gets written in html. I can't really put my finger on why things went bonkers, but if I do my RenderPartials before my form and then begin my form with the text entry field and the hidden VideoId, the default ModelBinder works just fine. I was beginning the form, writing the hidden VideoId, rendering several partial views, create my CommentText field, and then closed the form out. The CommentText field would get bound just fine. The hidden VideoId would not. Maybe I missed a rule somewhere about using RenderPartial.

For completeness, the partial view I was rendering took a Comment object and just wrote out it's CommentText data. Several of these objects would exist for a single Video object. All of this data was in a custom type and passed into the View (the main view) as it's Model. This partial view did not have a form and did not have any data entry fields.

View 2 Replies

MVC :: Model State Doesn't Contain Model Values

Aug 2, 2010

when I use Html.HiddenFor( model => model.OwnerId ) to create a hidden field, the value assigned to that field is zero. When I use <input type="hidden" value="<%: Model.OwnerId %>" /> to add the hidden field to the form, the value is assigned correctly.

Why would Html.HiddenFor( model => model.OwnerId ) not get the correct value from the Model object? Am I supposed to load model state somehow separate from returning the model object from the action method? Here is the view:

[Code]....

The Create action method is relatively straight forward.

public ActionResult Create( ... )
{
ViewStockItem item = new ViewStockItem();
item.ActionCode = ActionCode.Add;
if (item.OwnerId == 0)
item.OwnerId = 7;
BookOwner owner = db.BookOwners.Single(c => c.OwnerId == item.OwnerId);
item.OwnerName = owner.OwnerName;
return View(item);
}

View 4 Replies

Should Data Annotations Be On The Model Or The View Model

Dec 15, 2010

I've been used to decorating data model classes with data annotation attributes, but the purist in me baulks slightly at including purely presentational attributes such as display format here. I am, however, quite happy to keep validation centric attributes here. One good reason I have to continue keeping all annotations etc. in the data model is that my view model aggregates data model classes, e.g.

my ViewModelBase.DetailItem<TEntity> property in the view model is just a reference to an entity class in my data model. If I wanted to move presentational annotations to the view model, I would have to quite radically revise my design to one where I duplicate data model properties in my view model and use an object mapping tool to populate view model objects based on data model objects.

[code]....

View 2 Replies

MVC :: View Model To Convert To Domain Model?

May 4, 2010

Say I got a domain model as follows: (and my repository expect an instance of this object)

[Code]....

And a view model (which my views are based on)

[Code]....

At the moment I got it like this and have my controller action manually create a new Person object from the PersonModel object before passing it on to the repository, which does not feel right.

So I tried to have PersonModel inherit from Person and pass that to the repository (also tried casting the PersonModel to a Person object first), but that don't work out.

What's the right way to have PersonModel automatically cast to Person? I want to keep this logic as my current structure allow me to keep things really loosely coupled, with the repository layer not having a clue how it's being used.

View 1 Replies

MVC :: Model Validation For File Upload?

Aug 17, 2010

My MVC 2 app includes a simple file upload within in a strongly typed view and I am trying to figure out how to apply model validation to the file name. Is this possible? Is there better way to do file upload within an MVC app?

The salient parts of the (prototype) controller code are:

[Code]....

The Create view code was generated with VS2010 and then modified to support file upload and client side validation:

[Code]....

View 3 Replies

Localize Default Model Validation In Mvc 2?

Jul 1, 2010

[Required]
[DisplayName("my date")]
public DateTime? DateReg { get; set; }

so if the user is going to pass in an invalid datetime value he will get this message "The value '02.07.201022' is not valid for my date."

View 1 Replies







Copyrights 2005-15 www.BigResource.com, All rights reserved