views:

62

answers:

3

Hi All,

I'm using ASP.NET MVC and Entity Framework. I'm going to pass a complex entity to the clent side and alow the user to modify it, and post it back to the controller. But I don't know how to do that and whether the client side entity will lost relationship tracking of EF as it is detached from object context.

Any ideas? Thanks in advance!

A: 

The entity will be detached. You will need to fetch the entity again, update the properties, and then commit the changes. Alternatively you could reattach the entity, but this can be tricky when you are dealing with multiple related entities being attached at the same time. If this is the case for you, check out http://www.codeproject.com/KB/architecture/attachobjectgraph.aspx.

Jeremy
+2  A: 

ASP.NET MVC is capable of Model Binding complex objects and it's quite good at it. An easy way to do this is to name your view fields that same as the properties for your object. That way in your action method that the form posts to you only need the complex object as a parameter. Example:

<% using(Html.BeginForm()) { %>

    <%= Html.TextBox("Property1") %>
    <%= Html.TextBox("Property2") %>
    <%= Html.TextBox("Property3") %>
    <%= Html.TextBox("Property4") %>
    <%= Html.CheckBox("PropertyBool") %>
    <%= Html.TextBox("Property5") %>

<% } %>

Which posts to an action method like so:

public ActionResult Index(ComplexObject complexoObject)
{

}

That's a fairly simple example as you could have different form controls in the view for corresponding properties of the object. If your object is very complex you could always write your own model binder for it and over-ride the default model binder.

DM
Yeah, that's true. But what I'm posting back is a big questionaire which contains more than 100 questions. they are contained in a list. How can I post that back? Thanks!
Roy
http://marcomagdy.com/2009/09/03/asp-net-mvc-model-binding-form-inputs-to-action-parameters/
queen3
DM
A: 

You are saying that you display a list of 100 questions on one single page? I hope you are not doing that. First of all, this is not very user friendly. It involves a lot of scrolling down, user can get lost, its error prone and if something goes wrong he has to do it all over again.

A better approach is one or few questions at a time. With Next/Prev buttons for moving between them.

You could make it even easier for yourself and forget about postbacks and go the AJAX way - issue a post request to some Json service the AJAX way. And save the progress after each question, so if something goes wrong user can resume later from where he left off. It will be much more maintable, faster and user friendlier.

mare