0

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.

2 Answers 2

2

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 
}
Sign up to request clarification or add additional context in comments.

2 Comments

Also, just to add.. @model type declaration doesn't work in MVC 2
This works :), but this is not what I asked for. I knew this solution before hand. I wanted to know where I am going wrong with this code. In the end it came down to a casting issue.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.