Question

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.

Was it helpful?

Solution 2

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()))%>

OTHER TIPS

I think, Instead of Passing the Querystring value in ViewData, You should set it as the Property value of your ViewModel/ Model and pass that to your View.

public ActionResult Data()
{
  YourViewModel objVm=new YourViewModel();
  objVm.Param=Request.QueryString["Param1"];
  return View(objVm);
}

Now in your Strongly typed View, use it like this

@model YourViewModel 

@using(Html.BeginForm())
{
  @html.HiddenFor(@m=>m.Param);
  <input type="submit" value="Save" />
}

Now Param value will be available in yout HttpPost action method

[HttpPost]
public ActionResult Data(YourViewModel objVm)
{
  string param=objVm.Param;
  //Do whatever you want with param 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top