Prasad
Prasad

Reputation: 121

Passing data from view to partial view in MVC

I want to send 3 parameters from View to Partial View and i am opening the partial view into new browser tab.

Parameters are

var Hdata = 'some value'; 
var abc = document.getElementById('mycontrol1');
var abcd = document.getElementById('mycontrol2');

These 3 parameters i want to send it to Partial view. The code is like

window.open('@Url.Action("Action", "Controller")', '_blank');

So how can i pass data to Partial view.

Thanks in Advance.

Upvotes: 9

Views: 25612

Answers (2)

Rajshekar Reddy
Rajshekar Reddy

Reputation: 19007

From what I can understand from your question and the code provided is, You are extracting some values from DOM elements and then on some event trying to oepn a view in new tab. Now you want these data of the DOM elements to be available in the new view as well. If this understanding is correct then you can do like below.

You already have this.

var Hdata = 'some value'; 
var abc = document.getElementById('mycontrol1');
var abcd = document.getElementById('mycontrol2');

having these values now you just need to hit a controller which will render the view. So you can pass these values to controller by constructing a query string.

var URL = '@Url.Action("Action", "Controller")' + '?Hdata=' +Hdata + '&abc='+abc +'&abcd='+abcd;
window.open(URL , '_blank');

Also your controller must be like so.

 public ActionResult YourControllerName(string Hdata,string abc, string abcd)
 {
    ViewBag.Hdata = Hdata;
    ViewBag.abc = abc;
    ViewBag.abcd= abcd;

    return PartialView();
 }

Now you will have the data available in your partial view via ViewBag.

OR the cleaner way would be to have a model to receive and pass the data.

 public class YourModel
 {
  public string Hdata {get;set;}
  public string abc {get;set;}
  public string abcd {get;set;}
 }

Then the controller would be

 public ActionResult YourControllerName(YourModel pageData)
  {
    return PartialView(pageData); //this requires your view to use model of type YourModel
   // OR
   // ViewBag.PageData = pageData;
   // return PartialView();
  }

Upvotes: 1

Nico
Nico

Reputation: 12683

The easiest way is in the query string. Something like.

window.open('@Url.Action("Action", "Controller", new { data1 = Model.Data1 })', '_blank');

Then you are passing data to your new window. However now you have exposed your data to the URL and handling complex types can get difficult. If possible would be better to pass an identifier to your action that lets you rebuild the model you wish to display in the window.

window.open('@Url.Action("Action", "Controller", new { id = Model.Id })', '_blank');

Upvotes: 0

Related Questions