Lists in ViewModel lost after send to controller

时间:2019-04-16 22:16:53

标签: c# asp.net-mvc-5

I have a View Model in a detail screen. It shows fine all the information but when I send the vm to a print function which do nothing but return partial view I loos the custom lists of phone numbers and emails. They show as empty lists inside the Print function. Any idea why?

My view model

             public List<PhoneDetails> Phones {get; set; }
             public List<EmailDetails> Email { get; set; }

My Print view

   @if (Model.Phones.Count > 0)
        {
            foreach (var phone in Model.Phones)
            {
             <p>
                phone.PhoneType Phone: <span class="policy-bold">phone.PhoneNumber</span>
            </p>
            }
        }
        else
        {
            <p>Phone Number: <span class="policy-bold">N/A</span></p>
        }
    </div>

My print function

  public virtual ActionResult Print(PolicyDetailViewModel viewModel)
    {

        return PartialView("Print", viewModel);
    }

The redirect method which was the problem is:

<li role="presentation" class="pull-right"><a href="@Url.Action("Print", "ControllerName", Model)" target="_blank">Print / Full Detail View</a></li>

1 个答案:

答案 0 :(得分:1)

There are two solutions to pass your list to controller :
1) using the form tag :

@using(Html.BeginForm( // your paramas ))
{
    @if (Model.Phones.Count > 0)
        {
            foreach (var phone in Model.Phones)
            {
             <p>
                phone.PhoneType Phone: <span class="policy-bold">phone.PhoneNumber</span>
            </p>
            }
        }
        else
        {
            <p>Phone Number: <span class="policy-bold">N/A</span></p>
        }

}

2) Using ajax :
this is just an example :

var premisesViewModel = $('form').serializeObject();
$.ajax({
        url: form.attr('action'),
        type: 'POST',
        dataType: "json",
        contentType: 'application/json',
        data: JSON.stringify(premisesViewModel),
        success: function (data) {
            alert('done');
        }
    });