Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 228
Prasad Avatar asked Mar 11 '16 05:03

Prasad


People also ask

How pass data from one view to another view in MVC?

In this case it will be set to POST. The Form consists of a TextBox and a Submit Button. When the Submit Button is clicked, the Form gets submitted and the TextBox value is sent to the Controller's Action method of the Destination View. Inside this View, the data from the ViewBag object is displayed using Razor syntax.

Can we pass data from view to controller?

There are four ways to pass the data from View to Controller which are explained below: Traditional Approach: In this approach, we can use the request object of the HttpRequestBase class. This object contains the input field name and values as name-value pairs in case of the form submit.


1 Answers

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();
  }
like image 70
Rajshekar Reddy Avatar answered Sep 28 '22 06:09

Rajshekar Reddy