Search code examples
asp.net.netasp.net-mvcasp.net-mvc-2viewdata

Passing Querystring data to a Model in ASP.NET MVC 2


I have a strongly typed view inheriting from a POCO class. I want to initialize the property of a model with a Querystring value at the time when view loads.

On the View Load I am using ViewData to the save the code :

 public ActionResult Data() { 

    ViewData["QueryStringValue"] = this.Request.QueryString["Param1"]
    return View();

    }

In the HTML markup, I am using this code to initialize the model property in a hidden variable

<%:Html.HiddenFor(m=>m.Param,
Convert.ToInt32(Html.Encode(ViewData["QueryStringValue"]))) %>

m.param is a byte type.

URL of the request is somewhat like this : http://TestApp/Data/AddData?Param1=One

On View Save event, I am using model binding but issue is that I don't get to see the value of param initialized in the controller. It is always NULL.

My Save Event maps to a controller :

[HttpPost]
public ActionResult SaveData(MyData d)
{
string paramValue = d.Param; //this always returns null

BO.Save(d); }

I inspected the HTML source and saw that the value of the hidden field itself is blank. Not sure why this is happening since the below code works and shows the param value in a heading element

<h2> <%=Html.Encode(ViewData["QueryStringValue"]) %> </h2>

I have no idea where I am going wrong on this.


Solution

  • Just made this work, Issue is with this line:

     <%:Html.HiddenFor(m=>m.Param,
    Convert.ToInt32(Html.Encode(ViewData["QueryStringValue"]))) %>. I stated in the question that m.Param is of type byte. I figured out that issue was with casting.
    

    I tried this code and it worked

    <%:Html.HiddenFor(m => m.Param, (byte)Convert.ToInt16(this.Request.QueryString["Param1"].ToString()))%>