ct5845
ct5845

Reputation: 1588

MVC3 "Dynamic" Parameter List Model and View

Need a hand/guide of creating a view that handles a list of parameters which we get the name of during run time, currently during the postback it just won't return anything, using the MVC html helpers.

My Models

public class Parameter {
  public string Name {get; set;}
  public string Value {get; set;}
}  

public class Job {
  public List<Parameter> parameters {get; set;}
}

My Views

Add View

@model Models.Job
@using (Html.BeginForm("Add","Job")) {
  @foreach (var parameter in Model.Parameters)
  {
    @Html.Action("AddParameter","Job", parameter)
  }
 </fieldset>
}

AddParameter View

@model Models.Parameter

<div class="editor-label">
    <label for="@Model.Name">@Model.Name</label>
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.Value)
</div>

when this get's posted back to the below controller the list is not populated. I think i'm probably going about it in completely the wrong way but no idea how to really implement it. It seems the "dynamic" parameter concept is the thing really throwing me. Will this approach work and i've just got some things wrong? or do i need to look at another way of doing it?

Controller

[HttpPost]
public ActionResult Add(Job model)
{
    //Do Something
    return PartialView();
}

Upvotes: 2

Views: 3763

Answers (1)

AJC
AJC

Reputation: 1893

Your problem is related to returning a List from the view... check this post by Phil Haack:

Model Binding To A List

Here you can see I ran into the same problem. The solution proposed guided me in the right direction but it wasn't the one I used, I used Phil's post.

My Post

Hope this helps...

EDIT: To clarify, what you need to do is change your AddParameter View into an EditorTemplate and use it as instructed in the above post by Phil.

Upvotes: 2

Related Questions