开发者

do a HTTPPOST MVC2

I have a MVC2-application. in this application I have a strongtyped view contending the modell NewHorseModel:

public class NewHorseModel
{
    public List<Category> Faehigkeit { get; set; }
}

public class Choice
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Beschreibung { get; set; }
    public bool Selected { get; set; }
}

public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Beschreibung { get; set; }
    public List<Category> Subcategories { get; set; }
    public List<Choice> Choices { get; set; }
    public int Parent { get; set; }
}

The View looks like this:

<p>
    <input faehigkeit_ID="1" id="Selected" name="Selected" type="checkbox" value="true" />
    <input name="Selected" type="hidden" value="false" />
    Mitteltrab
    <input id="Id" name="Id" type="hidden" value="1" />
</p>
<p>
    <input faehigkeit_ID="2" id="Selected" name="Selected" type="checkbox" value="true" />
    <input name="Selected" type="hidden" value="false" />
    Arbeitstrab
    <input id="Id" name="Id" type="hidden" value="2" />
</p>
<p>
    <input faehigkeit_ID="3" id="Selected" name="Selected" type="checkbox" value="true" />
    <input name="Selected" type="hidden" value="false" />
    Trab versammelt
    <input id="Id" name="Id" type="hidden" value="3" />
</p>
<p>
    <input faehigkeit_ID="11" id="Selected" name="Selected" type="checkbox" value="true" />
    <input name="Selected" type="hidden" value="false" />
    Trab
    <input id="Id" name="Id" type="hidden" value="11" />
</p>

The view is created like in this post: Categories and Subcategories MVC2

now I want to do a post, but how to get the datas? When I do a post like this:

[HttpPost]
public void myAction(NewHorseModel newHorseModel)
{
    // ...
}

Faehigkeit in NewHorseModel is null

Here my ASPX Code:

<div id="Div2">
    <%
    foreach (Category item2 in Model.Faehigkeit)
    {
        Html.RenderPartial("Faehigkeit", item2);
    }
    %>
</div>

The partial view Category (strong typed model Category):

<%
if (Model.Choices != null)
{
    foreach (var item in Model.Choices)
    { 
        Html.RenderPartial("Choice", item);
    }
}
if (Model.Subcategories != null)
{
    foreach (var item in Model.Subcategories)
    {
        Html.RenderPartial("Faehigkeit", item);
    }
}
%>

And the partialview Choices (strongtyped model choice)

<p>
    <%: Html.CheckBoxFor(m => m.Selected, new { faehigkeit_ID = Model.Id }) %>
    <%: Model.Name %>
    <%: Html.HiddenFor(u=>u.Id) %>
</p>

Update Next test: in the Faehigkeit.ascx partial I have added this code:

     <input type="hidden"  name="Faehigkeit[<%=Model.Id%>].Id" value="<%=Model.Id%>" />
<input type="hidden" name="Faehigkeit[<%=Model.Id%>].Name" value="<%: Model.Name%>" />

in the Choices.ascx partial I have added following code:

<input type="checkbox" name="Faehigkeit[0].Choices[<%=Model.Id%>].Selected" />

I don't need to know which choice is in wich category. I kust need to know which choice ID is checked and which on not.

The HTML-Output looks like this:

  <input type="hidden"  name="Faehigkeit[1].Id" value="1" />
<input type="hidden" name="Faehigkeit[1].Name" value="Qualit&#228;t der Gangarten" />
<input type="hidden" name="Faehigkeit[1].Choices[4].Id" value="4" />
<input type="checkbox" name="Faehigkeit[1].Choices[4].Selected" />

My controler looks like this: [HttpPost]

public ActionResult CreateNewHorse(NewHorseModel collection)
    {
        if (User.Identity.IsAuthenticated)
        {


            return View();
        }
        else
        {
            return View("Account/LogOn");
        }

    }

If I try to get the value of "Faehigkeit开发者_运维知识库" -> "Choices" Every thing is Null (the Name of the "Faehigkeit", the ID of "Faehigkeit", and there are no choices An image that shows the content of the NewHorseModel during debuging: http://i.stack.imgur.com/6yLZW.png

Thank you very much!


There are 2 blog posts that I've written and will address your problem:

  1. How to post IList<T> to controller actions is explained here and will guide you from start to finish so you'll understand how it actually works and why.

  2. And since you may have have complex JSON objects on the client side and would like them to be model bound on the server in your action method (as is in your case), this post may be as well an interesting read. It explains the problem of sending complex JSON objects and provides a simple jQuery plugin that converts client objects into a form that will easily be data bound to your strong type action method parameters.

Note: There's also the possibility of using JsonValueProviderFactory as explained by Phil Haack, but that solution requires changes on the client as well as on the server side (because you're using MVC2).

Based on your code

You've only provided some parts of your code (and some that aren't really relevant but anyway) and I'm going to make an observation for your case.

All input fields that you wish to model bind on the server need to have correct names. From the rendered checkbox names we can see that is not the case at all.

Based on your model, your inputs should be named as (never mind input types because only you know which ones should be rendered and as which type):

<!-- erste fähigkeit -->
<input name="Faehigkeit[0].Id" />
<input name="Faehigkeit[0].Name" />
<input name="Faehigkeit[0].Beschreibung" />
<input name="Faehigkeit[0].Subcategories[0].Id" />
<input name="Faehigkeit[0].Subcategories[0].Name" />
...
<input name="Faehigkeit[0].Choices[0].Id" />
<input name="Faehigkeit[0].Choices[0].Name" />
<input name="Faehigkeit[0].Choices[0].Beschreibung" />
<input name="Faehigkeit[0].Choices[0].Selected" />
...
<input name="Faehigkeit[0].Choices[x].Id" /> <!-- "x" could be any number -->
...
<input name="Faehigkeit[0].Parent" />
<!-- zwite fähigkeit -->
<input name="Faehigkeit[1].Id" />
...
<!-- usw. -->

Based on this complex hierarchical model this form can be huge. And you probably don't wish to send all properties because you only need some that are relevant. But the main thing is that input naming should be as described.

Extremely important: I should point out that indexes (ie. Faehigkeit[0]) are not supposed to relate to IDs, but are rather array/list item indexes. They should be consecutive so they should always start at 0 and should be incremented by 1 to the last N hence should have no gaps whatsoever. Believe me I've tested that when I was writing my blog post. Otherwise model binding on the server will fail. Make sure you pass this requirement! Based on your edited question this is not the case, because you're putting in IDs instead of indexes.

If you'd transfer your data as JSON to the client, you'd have an object on the client as:

var data = {
    Faehigkeit: [
        {
            Id: 1,
            Name: "Some name",
            Beschreibung: "Some description",
            Subcategories: [
                { ... },
                { ... },
                ...
            ],
            Choices: [
                { ... },
                { ... },
                ...
            ]
        },
        { ... },
        ...
    ]
};

And if your client side view manipulated this object directly you could then afterwards send it back to the server by means of jQuery Ajax call ie:

$.ajax({
    type: "POST",
    url: "someController/myAction",
    data: $.toDictionary(data), // this is my jQuery plugin mentioned earlier
    success: function() { ... },
    error: function() { ... }
});

So the choice is yours, but in either case, field names should be correct otherwise your model won't be bound to your parameter and you won't be able to use it.

You could try with <%= Html.EditorFor(m => m); %> but that may not be the kind of form you'd like to use. In such case manual input naming would have to be used. Or you can as well write some custom code.

One of the ways would be to chaneg your partial views mode types to become for instance Tuple<string, Category>. String would tell it what string should be pre-pent to your field names.

Html.RenderPartial("Faehigkeit", Tuple.New("Faehigkeit[0]", item2));

And then when you go along, previous data should be always added so your subcategories' lists and their respected subobjects will have correct input form names.

Not nice, but I suppose it's the only way to make it.


Usually if you put the HttpPost as an attribute of your action, its something like:

[HttpPost]
public void myAction(NewHorseModel newHorseModel)
{;}

Then put the class type as your argument it should autobind it for you, if there is anything crazy that you need to do, or are posting from an external non ASP page to this action you can just use the FormCollection (i think) as your argument and thats a glorified Dictionary containing all your elements and values.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜