Question

I have a simple view like this:

@using MyProject.WebClient.Models
@model LoginClienteModel

<h1>@ViewBag.Title</h1>
@{
    <text>
        <h2>
            <span>Olá @Model.Login . </span>
        </h2>
        <h3>
            <span>Info: (@Model.ProperyOne)</span>
        </h3>
    </text>
}
<br/>
@Html.ActionLink("Option 1", "OptOne", "Home", new {pdModel = new OptOneModel{Login = Model.Login,Data = DateTime.Now.Date}});

When this view is showed, all data from model is displayed correctly. You can see I've another ActionLink, pointing to action OptOne. That action requires a parameter pdModel of type OptOneModel. As you can see, I instantiate it using current model values. But when my Action is executed, Login property is null, only Data is not null.

  public ActionResult OptOne(OptOneModel pdModel)
  {
      return View(pdModel); // <-- Here only Data property is not null
  }

I'm lost. I can't see what is wrong with that.

Was it helpful?

Solution

Unfortunately, you can't pass a complex type into a route value that way for an ActionLink. Manual invocation of an Action, I believe you can, but not for a link. So:

@Html.ActionLink("Option 1", "OptOne", "Home", new {pdModelId = Model.YourUniqueId, dateRendered = DateTime.Now.Date});

Meanwhile, server side:

  public ActionResult OptOne(int pdModelId, DateTime dateRendered)
  {
      // retrieve model again based on your Id
      return View(pdModel);
  }

OTHER TIPS

You cannot use hyperlink to pass Model. It only work with Post.

Instead, you can use routeValues to generate query string.

@Html.ActionLink("Option 1", "OptOne", "Home", 
   new { Model.Login, Data = DateTime.Now.Date }, null)

public ActionResult OptOne(string login, DateTime data)
{
    // Do something with login and data.
    return View();
}

Use either ActionLink overload variation,

ActionLink(string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)

@Html.ActionLink("Option 1", "OptOne", "Home", new OptOneModel{ Login = Model.Login, Data = DateTime.Now.Date}, null);

OR

ActionLink(string linkText, string actionName, object routeValues)

@Html.ActionLink("Option 1", "OptOne", new OptOneModel{ Login = Model.Login, Data = DateTime.Now.Date});

hope this helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top