Html.DropDownListFor<> And Complex Object In MVC2?

Apr 4, 2010

I am looking at ASP.NET MVC2 and trying to post a complex object using the new EditorFor syntax.I have a FraudDto object that has a FraudCategory child object and I want to set this object from the values that are posted from the form.Posting a simple object is not a problem but I am struggling with how to handle complex objects with child objects.I have the following parent FraudDto object whcih I am binding to on the form:

public class FraudDto
public FraudCategoryDto FraudCategory { get; set; }


View 1 Replies

Similar Messages:

How To Send Complex Types To MVC2 Controller Via Jquery (Ajax )

Feb 22, 2011

I am posting a Jquery Json serialized object to my controller but not all of the data is getting passed. One of the members is a complex type that is also Json serialized. This is the one that isn't getting through to the controller.

Here is the class I'm passing to my controller via Ajax post. Note the complex type, RoutingRuleModel.



Problem: SourceCodeModel contains correct values EXCEPT for it's complex member: RuleModel, which comes back as a RoutingRuleModel with default (null or 0's) values.

View 1 Replies

C# - Best Way To Edit And Update Complex Viewmodel Objects Using Mvc2 And Entity Framework?

Apr 2, 2010

I have a table in my database with a one to many relationship to another table, which has a relationship to a third table:


This seems to work fine. My question to you good folks: Is there a correct way to do this? I tried following the making a custom model binder per the blog link I posted above but it didn't work (there was an issue with reflection, the code expected certain properties to exist) and I needed to get something going ASAP. PS - I tried to cleanup the code to hide specific information, so beware I may have hosed something up.

View 1 Replies - How To Write A Simple Html.DropDownListFor()?

Jun 16, 2010

I'm new in ASP.NET MVC 2 and I'd like to write a very simple dropdown list which gives static options. For example I'd like to provide choices between "Red", "Blue", and "Green".

View 2 Replies

Change Width Of Html.DropDownListFor()?

Jun 15, 2010

I have small design question about


How can i change width of html.DropDownListFor() ??

For example by css.

View 2 Replies

MVC :: Html.DropDownListFor - Setting Selected Option?

May 20, 2010

I have the following code:


However, the wrong option is selected, and when I view page source, it renders like this:

Why is this occurring?

View 3 Replies

Mvc 3 Pre-select Html.DropDownListFor Not Working In Nerd Dinner?

Jan 26, 2011

Learning about dropdown lists, Im trying to add a RSVP create page for nerddinner as in Scott Gu's blog with a Html.DropDownListFor listing available dinners. I can get the dropdown list populated but I cannot get the dropdown to pre select the value ("Sample Dinner 2") I want. Im using an initilizer to seed a few dinner objects in the db. The database is sql ce 4 using a EF 'code first approach'. Sorry I know this is a v common problem and hate to ask, but honestly have spent quite some time on this but cant get it to work:


public class RSVPViewModel
public SelectList DinnersList { get; set; }
public RSVP Rsvp { get; set; }
public string SelectedItem { get; set; }

So is not preselecting the dropdownlist with the value "Sample Dinner 2" when the page loads. The list displays ok and sets the correct DinnerID when I make a selection and click Submit.Tries this also:

@Html.DropDownListFor(x => x.SelectedItem, Model.DinnersList)

but doesnt set or bind to Rsvp.DinnerID.This preselects from the list but doesnt bind (or set Rsvp.DinnerID)


I want to keep it mvc3 so want to implement with strong type using ViewModel approach (no ViewData) and preferably using Html.DropDownListFor (not Html.DropDownList).Viewbag seems unnecessary for this case.Thinking I should be using a selectList of selectListItems I tried this verbose approach :

RSVP rsvp = new RSVP();
string selected = "2";
List<SelectListItem> dinners = new List<SelectListItem>();

foreach (Dinner dinner in dbc.Dinners.ToList())
SelectListItem slDinner = new SelectListItem();
slDinner.Value = dinner.DinnerID.ToString();
slDinner.Text = dinner.Title;
slDinner.Selected = (slDinner.Value == selected);
var dinnersList = new SelectList(dinners, "Value", "Text", selected);
var viewModel = new RSVPViewModel { DinnersList = dinnersList, Rsvp = rsvp, SelectedItem = selected };

However still no work. Should I be making use of the ViewModel SelectedItem property in: @Html.DropDownListFor.. somehow? Something like :@Html.DropDownListFor(x => x.SelectedItem, Model.DinnersList)but how to I get a selected value to set Rsvp.DinnerID. I think thats called binding.

View 2 Replies

MVC :: Binding Complex Lists To An Object?

Jan 26, 2010

I'm having trouble finding a good tutorial on binding complex lists to an object. Essentially we have currencies that are user defined, we need to generate a form for each currency to allow the user to input exchange rates. I think I'm doing my list properly according to this post, however I'm not getting any data bound. here is my ASPX snippit.

Here is my form data object and associated objects.


Here is the html that is rendered.[Code]....

I'm having trouble finding a good tutorial on binding complex lists to an object. Essentially we have currencies that are user defined, we need to generate a form for each currency to allow the user to input exchange rates. I think I'm doing my list properly according to this post, however I'm not getting any data bound. here is my ASPX snippit.


View 1 Replies

C# - Unable To Construct An Entity (complex) Object From A Query

Jun 8, 2010

I am very new to entity, sql, c#, and so this might be something easily fixed. I am attempting to display all the inactive products stored in my table called products in a datagrid.

var productQuery = from b in solutionContext.Version
where b.Product.Name == search && b.Product.ActiveNumber > b.VersionNumber
select new Product
Name = b.Product.Name,
Description = b.Product.Description,
ID = b.ID,
LastNumber = b.Product.LastNumber,
MiddleNumber = b.Product.MiddleNumber,
ActiveNumber = b.Product.ActiveNumber,
LastModified = b.Product.LastModified,
ParentID = b.Product.ParentID,
ProductType = b.Product.ProductType
ProductsGrid.DataSource = productQuery;

I am getting this error: $exception {"The entity or complex type 'SolutionsModel.Product' cannot be constructed in a LINQ to Entities query."} System.Exception {System.NotSupportedException}

View 1 Replies

MVC :: Html.DropDownListFor() - Can Specify A Value Of "0" For The OptionLabel

Jun 24, 2010

In my view I have this:


The SiteId is of the type System.Guid. When this is posted to the action of my controller, then ModelState.IsValid returns false, which is actually normal because I have this in the generated HTML:


How can I make sure that the first option is <option value="0"></option>?

View 5 Replies

MVC :: Saving A Complex Child Object After Post (LINQ To SQL Model Binding With MVC)

Jan 6, 2011

I am using ASP.Net MVC2 and LINQ to SQL. I am using DataAnnotations and model binding in conjunction with a Form/View and its working beautifully well. Loving that.. My view is an "Add new Employee" form that's adding a new "Employee" complex object. Every Employee also has a child complex object called an "Address".
I am using the bound Html helpers in the view, such as Html.TextBoxFor(model => model.NewEmployee.FirstName) for example. Working beautifully well, validating beautifully well both client and server and coming into the controller fully populated and ready to be saved! Exciting.. ModelState.IsValid returns true and I go to save the new Employee.

The Employee is created fine but the system also creates a blank/new Address record in my Addresses table even when the Address fields are blank! How can I prevent any Address from being created, in situations where I ONLY want to create a new Employee with no Address. An example is when the user supplies an existing Address, then I wish to simply set the new Employee's AddressID to that of an existing physical address (I hope that makes sense). But it could apply to any situation where you need to create a new complex object, but you don't wish for LINQ to create any of its child complex objects. I have tried setting NewEmployee.Address = null after it is received in the controller, but even after that, a blank/new Address is still created. Even if I try NewEmployee.Address = SomeExistingAddress, it does correctly link the Employee to the existing Address, but it STILL goes off and creates another redundant new/blank address record! Which is really weird..

View 10 Replies

MVC + LINQ To SQL Model Binding - Saving A Complex Child Object After Post

Jan 5, 2011

I have a "Create New Employee" ASP.Net MVC form. My complex object is an Employee and an Employee has an Address, which is another Complex object. On my View/Form I collect all required values for both the Employee and the Address. I'm using the bound HTML helpers such as: Html.TextBoxFor(model => model.EmployeeAddress.StreetName)


Html.TextBoxFor(model => model.NewEmployee.FirstName)

This is all working beautifully well. Model binding is working like a dream, both server side and client side validation using DataAnnotations is working beautifully well and I am nicely receiving my populated complex objects as expected in the Controller.. Now I'm trying to save.. The Employee should always be newly created, because its an "Add New Employee" form. But sometimes the Address is an existing Address and I don't want to insert another one. Rather, I just want to link the Employee to the existing AddressID of the one that already exists in the database.

So I wrote a nifty GetExistingOrCreateNewAddress(Address PostedAddress) method which works great so I end up with the correct Address to use and link to the about to be saved Employee object. This is all happening in the same DataContext, so no problems there..

BUT even when I link the about to be saved Employee object to an existing Address, on save a new/empty Address row is created in my Addresses table. Even though the newly created Employee does link correctly to the existing Address I told it to! Why is it so??? And how can I save the new Employee without LINQ automatically creating a blank Address for me. Because I'm explicitly specifying an existing Address it should be linked to instead!

public ActionResult CreateEmployee(EmployeeDetailsViewModel NewEmployeeDetails)
if (ModelState.IsValid)
EmployeeRepository ER = new EmployeeeRepository();
// Fetch or Create the appropriate Address object for what has been entered
Address ActualAddress = ER.GetExistingOrCreateNewAddress(NewEmployeeDetails.EnteredAddress);
// Link this Address to the "about to be saved" Employee
NewEmployeeDetails.Employee.Address = ActualAddress;
// Lock it in..

View 2 Replies

AJAX :: How To Send Parameters To Custom Complex Business Object To WCF Service Using JQuery

Jul 23, 2013

I am trying to call web service from jquery..trying following way but i am not able to pass to complex type parameter to WCF service.My wcf function is as follows

<Web.WebGet(UriTemplate:="/GetData?strErrMsg={strErrMsg}&chrErrFlg={chrErrFlg}", ResponseFormat:=WebMessageFormat.Json, BodyStyle:=WebMessageBodyStyle.Wrapped)> _
Function GetData(ByRef strErrMsg As System.Collections.Generic.List(Of String), ByRef chrErrFlg As String) As String
strErrMsg is System.Collections.Generic.List(Of String)

I am trying to call as follows

var Type;
var Url;
var Data;
var ContentType;
var DataType;
var ProcessData;
var parameters;


And I am able to call other methods in same way having string and integer parameter.I have gone through this but didnt get anything. URL...

View 1 Replies

C# - MVC2 IModelBinder And Parsing A String To An Object?

Feb 2, 2010

I have an object called Time

public class Time{
public int Hour {get;set;}
public int Minute {get;set;}
public static Time Parse(string timeString){
//reads the ToString()'s previous output and returns a Time object

So what I want is for the automatic model binding on the Edit or Create action to set this Time instance up from a string (i.e. feed the Parse method with the string and return the result).

The reason I am doing this is that I will have a DropDownList with selectable times. The value of each option will be the parser readable string.

View 2 Replies

MVC2 Error: No Parameterless Constructor Defined For This Object - How To Fix It

Dec 28, 2010

First I incorrectly had my node defined in /shared/web.config instead of the web.config in the root of the WebUI project. I also had not correctly defined my connection string within web.config. I have pasted the proper web.config sections below:


View 2 Replies

Embed A Flash Object In My MVC2 Application Home?

Sep 24, 2010

I need to put a Flash Object in my website developed on MVC2 .NET, however the third party who made it just gave me an html with this code.HTML errors apart I don't know how to put it on ASP.NET.

<table width="608" border="0" cellpadding="0" cellspacing="0" bgcolor="#F4F4F4">
<td height="412">
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase=",0,0,0" id="runtime" width="608" height="412" align="middle">
<param name="allowScriptAccess" value="sameDomain" />
<param name="movie" value="runtime.swf" />
<param name="menu" value="false" />
<param name="quality" value="high" />
<param name="bgcolor" value="#ffffff" />
<param name="FlashVars" value="Runtime_settingPath=modules/main/setting.xml&Runtime_isRemote=false&Runtime_init_module=module1&Runtime_init_scene=scene1.swf" />
<EMBED src="runtime.swf" FlashVars="Runtime_settingPath=modules/main/setting.xml&Runtime_isRemote=false&Runtime_init_module=module1&Runtime_init_scene=scene1.swf" quality=high bgcolor=#CCCCCC WIDTH="608" HEIGHT="412" NAME="runtime" swLiveConnect="true" TYPE="application/x-shockwave-flash" PLUGINSPAGE=""></EMBED>

View 4 Replies

C# - HTML Formatting Tags Being Ignored In MVC2?

Feb 28, 2011

I've looked around and can't find a solution for this and it's driving me mad.I've got a basic MVC2 app (C#) and am trying to display text from a database with the line breaks included. I've used the following:

<span class="fieldBlock"><%: Model.Description.Replace(System.Environment.NewLine, "<br />") %></span>

This is adding the tags to the returned string as I'd expect but when the page renders it actually displays the tag as is instead of rendering the newline. ie. the text seen by the user in the browser is:"Quisque justo erat, iaculis sit amet aliquam eu, porttitor in mauris.<br /><br />Maecenas nisi velit, euismod at molestie vitae, malesuada id turpis. Mauris diam nisl, pretium id molestie nec, posuere posuere neque.<br /><br />Cras sed lectus nisl."

View 1 Replies

How To Pass Html Table Data To Controller In Mvc2.0

Dec 15, 2010

I have a HTML table (grid). I want to pass the html table data to controller.(mvc 2.0)

View 2 Replies

MVC2 - Does Html.EditorForModel () Work On The Nested Data Model

Apr 26, 2010

My test shows it doesn't work. It ignores the nested data in model.

View 1 Replies

Pattern For Retrieving Complex Object Graphs With Repository Pattern With Entity Framework

Oct 13, 2010

We have an ASP.NET MVC site that uses Entity Framework abstractions with Repository and UnitOfWork patterns. What I'm wondering is how others have implemented navigation of complex object graphs with these patterns. Let me give an example from one of our controllers:


It's a registration process and pretty much everything hangs off the POCO class Person. In this case we're caching the person through the registration process. I've now started implementing the latter part of the registration process which requires access to data deeper in the object graph. Specifically DPA data which hangs off Legal inside Country.

The code above is just mapping out the model information into a simpler format for the ViewModel. My question is do you consider this fairly deep navigation of the graph good practice or would you abstract out the retrieval of the objects further down the graph into repositories?

View 2 Replies

Linq To Sql - MVC2 - Set ViewModel Values With Retrieved From Db Object's Values With DataAnnotations

Jan 8, 2011

Prior to using a ViewModel, I could easily pass the "soon to be edited" object directly to the view without needing to fuss over setting individual properties etc as the View conveniently accepted the Employee type directly..

public ActionResult EditEmployee(int? id)
EmployeeRepository ER = new EmployeeRepository();
Employee SomeEmployee = ER.GetEmployee(id.Value);
return View(SomeEmployee);

But now I'm using a ViewModel with DataAnnotations attributes applied over the top of various properties for validation purposes. Which creates a problem.. After fetching the "soon to be edited" object from the db, setting the ViewModel's values is suddenly a whole lot more complicated. I can't simply pass the retrieved object straight to the view, as the View now expects the VMEmployee type instead. I would like to be able to do something like:

public ActionResult EditEmployee(int? id)
EmployeeRepository ER = new EmployeeRepository();
Employee SomeEmployee = ER.GetEmployee(id.Value);
return View(new VMEmployee(SomeEmployee));

All paths seem to lead to a huge constructor which manually sets the values of each individual property. But I never had to do that before when I wasn't using a ViewModel. Model binding was a blessing! My objects also have complex child objects, which my form is also collecting values for, so this would be a huge/verbose task against DRY principals. I don't even really want to use a ViewModel, but am forced to because I need two different DataAnnotations rule sets for different validation scenarios applied to the same object.

All I want to do is be able to have two different DataAnnotations rule sets for different scenarios. I.e. public-facing www site vs internal-facing admin site. DataAnnotations doesn't seem to be flexible enough to easily cater for this common need. I've tried AutoMapper, but it throws an error saying it can't map my object types, I suspect because Employee was auto-generated by LINQ to SQL. What is the most elegant way to achieve this while sticking to DRY principals?

View 1 Replies

Can An HTML Object Tag Be Placed Inside An HTML Form Tag

Oct 13, 2010

I have a simple ASP.NET page that uses the VLC media player to play a video in IE. I also have four buttons to control the playback:

Play, Pause, Stop, and Mute

The four buttons call JavaScript functions that access the ActiveX control. When I click on any of the buttons, I get the following error in the JavaScript function:

"Microsoft JScript runtime error: 'vlc' is undefined".

However, if move the object tag for the vlc player outside the form tag, then the JavaScript works correctly, and I can control the video playback.

My question is why must the object tag be outside the form tag for this code to work correctly?


View 1 Replies

Unobtrusive Validation Optio With DropDownListFor MVC 3

Feb 16, 2011

Why is it that client validation is getting triggered saying that my Default Theme field is required even if I didn't specify a [Required] attribute in my model?

public class Site
public int SiteId { get; set; }
Required(ErrorMessage = "*")]
public string Title { get; set; }
[Required(ErrorMessage = "*")]

View 1 Replies

MVC :: How To Bind DropDownListFor Within Table Rows

Aug 3, 2010

I have a table, and each row has a column where its data is actually a select list. I want the user to be able to select a drop down item, and when they POST, it saves the Id of the selected item. Is this possible?

I'm trying to model a "Room" each room has a number of Jacks, there are 2 types of Jacks (Data/Voice) - this is the select list.


Something like this does not work. I created a stub in my view model


View 7 Replies

MVC :: Retrieve A DropDownListFor Value On Form Post?

Jul 18, 2010

I don't know how to retrieve a DropDownListFor value on form post and how to validate it.

This is my scenario:

HTML markup:




I'm not able to validate this dorpdown and when I test if the Model is valid I have to re-fill the Location property


otherwise I get an "object reference not set" error on post-back.

View 7 Replies

Copyrights 2005-15, All rights reserved