2

I'm trying to add a custom list of parameters (guids) to the controller. For testing purpose I got a simple class:

    public class MyVM
{
    public string Name { get; set; }
    public Guid  Id { get; set; }

    public List<MySubVM> MySubVms { get; set; }
}

public class MySubVM
{
    public string Name { get; set; }
}

And I show it on my page like this

@using (Html.BeginForm("DoPost", "Home", FormMethod.Post, new { id = "form", enctype = "multipart/form-data" }))
{

@Html.TextAreaFor(m => m.Name)
for (int i = 0; i < Model.MySubVms.Count; i++)
{
    @Html.TextBoxFor(m => Model.MySubVms[i].Name)
}

    <button class="btn form-control btn-success" type="submit" name="buttonType" value="SaveEvaluation">Save</button>

    }

My controller method looks like this

        [HttpPost]
    public ActionResult DoPost(MyVM vm, List<string> guids)
    {
        return View();
    }

The Jquery

<script type="text/javascript">
var guids = [{ id: "6650f183-14fa-4247-9639-612c4ca0a232" }, { id: "97aa91a3-28a4-44f3-8d96-f93d5eaef558" }];
$.ready(function() {
    $('form').on('submit', function(event) {
        event.preventDefault();
    });
    $.ready(function() {
        $('form').on('submit', function(event) {
            event.preventDefault();
            $.post({
                type: 'POST',
                url: "/Home/DoPost",
                dataType: "json",
                data: { vm: $("form").serialize(), guids: guids },
                success: function() {
                    alert("Successful");
                }
            });
        });

    });
});

The issue is that the model gets posted correct into the controller, but the list of guids doesn't work. It's null all the time. I tried with string and it's the same problem there.

robertk
  • 2,461
  • 1
  • 27
  • 39
  • 1
    public ActionResult DoPost(MyVM vm, FormCollection form) { var guids = form["guids"]; ... – Tony Feb 24 '14 at 15:33
  • @Tony, you should make this an answer. – Maess Feb 24 '14 at 15:36
  • You should be able to have a `MainViewModel` that have 2 properties: `public MyVM vm{get;set;}` and `public IEnumerable guids` and in the controller use `MainViewModel` instead of `MyVM`. Where `GuidWithIdViewModel` is just a object with a guid property named Id – TryingToImprove Feb 24 '14 at 15:37
  • maybe try a `List` instead of string – CSharper Feb 24 '14 at 15:51
  • The GUID's are supposed to be collected from the view and does not come with the model, however issue is posting them back to the controller. @Tony that did not, it's null. – robertk Feb 24 '14 at 16:40

1 Answers1

0

Check out this link

jQuery.POST - pass another parameter with Form.Serialize() - Asp.net MVC 3

Then you should be able to do

public ActionResult DoPost(MyVM vm, FormCollection form) { 
    var guids = form["guids"];
}
Community
  • 1
  • 1
Tony
  • 1,297
  • 10
  • 17