Binding a dictionary containing a list in MVC4 - c#-4.0

I am having trouble posting a form that contains a Dictionary that contains an int as a key and a list of objects as a value.
Originally this was just a List of Objects and that worked fine and the type was:
List<MyObject> Fields
the working markup was
Fields_{0}__Property1
where {0} is the index of the object. To get it to post back the List of Objects I rendered the object with hidden fields like this:
#Html.HiddenFor(m => m.Property1, new { Name = string.Format("Fields[{0}].Property1", Model.Index), #id = string.Format("Fields_{0}__Property1", Model.Index) })
This worked well. Now however, we have a dictionary instead of a list and the list is inside the dictionary.
Now the type is:
Dictionary<int, List<MyObject>>.
I tested the format expected when we render the dictionary using Html.HiddenFor and so I've added hidden fields with the required format which now is:
#Html.HiddenFor(m => m.Property1, new { Name = string.Format("Fields[{0}][{1}].Property1", Model.Index, Model.Position), #id = string.Format("Fields_{0}__{1}__Property1", Model.Index, Model.Position) })
now the field id is
Fields_{0}__{1}__Property1
where {0} is the key of the dictionary and {1} is the index of the object in the list.
However on postback I now get
[InvalidCastException: Specified cast is not valid.]
System.Web.Mvc.CollectionHelpers.ReplaceDictionaryImpl(IDictionary`2 dictionary, IEnumerable`1 newContents) +131
I am guessing MVC is smart enough to render the fields of this complex object on the view but not smart enough to collect them back into the viewmodel when we post back.
I found this other guy who had a similar problem here and he solved it by not using a dictionary but instead creating a complex object. I'm wondering, however, if there's a quicker way that won't require me to rewrite the entire system.
Any ideas?
Update
I solved it by taking the source code of DefaultModelBinder and adjusting it.
I found the source here. I didn't create my own Binder because I want all the advanced functionality and validation rules to apply to all other elements.
Once I got the DefaultModelBinder compiling and working I found the part where the dictionary was failing to cast the complex items and wrote a custom Dictionary update method that solved the problem

You can always create a custom Model Binder to bind objects from request values exactly as you want. Simply create a class that implements the System.Web.Mvc.IModelBinder interface and implement the BindModel() method.

Related

Sharepoint Extenal List and Custom Field Types

I have an odd issue.
I have client that wants a sharepoint list what is populated from a WCFService. That part is working quite well.
I have a bdcmodel that is mapping the WCF data and I can create an external list from the bdcmodel as well so that is working fine.
The issue I have is that one of the properties in the model is actually a collection of entities called Attributes. The objects in this collection simply have 2 properties Name and Value so really they are just a key value pair.
The client wants to see the list of attributes of the parent entity in the external list. So there would be an Attributes column and within that column would be the list of attributes for each parent object.
Is there even a way to do this? I am looking into Custom Field Types, but it seems like these are really intended to be singular values.
How would I create a list within and external list?
Any help anyone can give would be great even if its just to tell me that there really isn't a stable way to do this so I can go back to the client and tell them we will need to build a custom list to support this because the OOB external list and custom fields and custom field types won't support this kind of nested listing.
I decided to set up the custom field as a string and when I get my collection in from the BdcModel I am serializing it to JSON and then passing it to the field. When the field is viewed in display, edit or new I have overridden the FieldRenderingControl and I am tiling the collection out that way.

System.ComponentModel.BindingList: Add(object) vs. AddNew()

What is the difference between the System.ComponentModel.BindingList methods Add(object) and AddNew()? The MSDN documentation says this:
Add: Adds an object to the end of the Collection<T>.
AddNew: Adds a new item to the collection.
It seems like both methods add an item to the collection, but Add(object) does it in one shot whereas AddNew() is slightly more complicated. My tests with Add(object) seem to be working, but I want to know if I am using the correct method.
So what is the difference between these methods?
AddNew() creates the object for you (that's why it doesn't have a parameter).
It's designed to be used by grids, which don't know how to create a new object to pass to Add().
AddNew() is very handy (it’s the well-known Factory design pattern) when you implement a class derived of BindingList().
It allows your code to initialize new items with values that depend on the list itself - e.g. a foreign key to the parent object if the binding list contains a list of children.

HashTable to Lwuit Table

Hashtable iHashtable=new Hashtable();
iHashtable.put("Name", "Jhon");
iHashtable.put("Address","India");
Enumeration iEnumeration=iHashtable.keys();
while(iEnumeration.hasMoreElements())
{
Object iresult1=iEnumeration.nextElement();
String iresult2=(String) iHashtable.get(iresult1);
System.out.println(iresult1);
System.out.println(iresult2);
My problem is I want to put the value at LWUIT table dynamically using the HashTable key and value,here is iresult1 and iresult2,using the key and value I want to create the LWUIT table where the value will be shown in the following form.
Name Jhon
Address India
please help me with the source code because i am new in J2me Application.please remember don't hardcore the key and value ,we get the value after parsing.
You can't do that since the JSON data isn't tabular but rather a hierarchy of nested hashtables and vectors based on the response from the server.
You can show the JSON data as a tree though by implementing the tree model interface, its not trivial but not too hard. You just need to return key objects for the keys (instead of strings) so they will allow including a reference to the value element.

Adding properties to an existing object retrieved using SubSonic

I think this is more of a polymorphism question but it applies to SubSonic table objects...
Here's the thing (and I love this one):
TblUser userObj = new TblUser(1);
Which fills userObj's properties with all of PK=1's goodies.
Now, I'd like to add more properties to the existing user object, for example, an ArrayList property of say, account numbers.
I've seen questions like this around - "add a property to an existing object...", but in this case, would it be most-recommended to create a user wrapper object, then have a TblUser property type, and my own other additional properties in this?
Ok, so it looks like once-again I have come up with a solution to this, but am still curious about the possibility of adding properties to existing objects.
All the generated SubSonic classes are partials so all you need to do to add extra properties/methods to them is to create your own partial class with the same name in the same namespace and the two will be merged at compile time. For example for your TblUser class:
public partial class TblUser
{
public List<AccountNumber> AccountNumbers
{
get
{
// Get and return the AccountNumbers
}
}
}

Removing ';#' from SharePoint ListItem data

In SharePoint many fields id-value pairs that are formatting like the following id;#value. This is further complicated with fields like multi-lookup where when extracting the value of that field can yield results like id_1;#value_1;#id_2;#value_2;#id_3;#value_3
I am wondering if there is any known built in function that will simplify this process and at the very least remove the IDs from the value.
Field value objects are stored as strings in the Sharepoint database. For simple values (e.g. "Hello world") this is simple enough. But for complex field values - such as an ID/value pair, how to store the entire value as a single string is obviously more complex as well. Each field value class in Sharepoint is responsible for its own storage implementation. ToString() is responsible for writing a string representation of the value; while the field value's constructor takes a string and is responsible for parsing that and setting all the properties on itself appropriately.
For example, the SPFieldUrlValue (which represents an description) has Url and Description properties. Creating a new SPFieldUrlValue(string fieldValue) object will parse the value and set the properties accordingly.
In order to get a true/correct (and often strongly-typed!) representation of the field value, you must know what type the field is, and what that field's value class is.
The SPField class has many derived classed
For example assuming a Lookup field type (that uses the ID;#value) you can check SPField.Type == SPFieldType.Lookup and then cast SPField to SPFieldLookup and use its overriden methods to get the records value.
See Custom Field Value Classes for more details
Also - If I remember correctly (I can't check this right now so DYOR) you can call .ValueAsText and .ValueAsHtml on the base SPField object and it will remove ID;# from the values.

Resources