erbo
erbo

Reputation: 21

How can I pass a string from View to Controller

public ActionResult Message()
{
    chartstype chartname = new chartstype();
    List<chartstype> listchart = new List<chartstype>();
    chartname.charttype = "Column";
    listchart.Add(chartname);
    TempData["name"] =listchart;
    TempData.Keep();
    return View();
}

And I want to change my code to be able to pass a string to chartname.charttype variable from View.

Upvotes: 0

Views: 94

Answers (3)

Djordje
Djordje

Reputation: 457

   public ActionResult Message(string message)

and make sure to see if string is null, because anyone can call this method trough url.

  if(string.IsNullOrWhiteSpace(message))
        {
            return new HttpStatusCodeResult(System.Net.HttpStatusCode.BadRequest);
        }

And then code in view

<form action="/controlerName/Message"  method="get or post , get is by default if you don't put this atribute">
<input id="txt1" type="text" name="message" value="set value here or in JS or let user enter value"/>

If you don't want textbox to be seen use

<input type="hidden" name="message" value="somevalue"/> Unless you want to call your method from javaScript using ajax?

Upvotes: 0

user8477754
user8477754

Reputation:

In controller

        public ActionResult Message(String chartName)
        {
            chartstype chartname = new chartstype();
            List<chartstype> listchart = new List<chartstype>();
            chartname.charttype = chartName;
            listchart.Add(chartname);
            TempData["name"] =listchart;
            TempData.Keep();
            return View();
        }

URL :https://www.example.com/Message?chartName=ABCD

Upvotes: 0

DarkSquirrel42
DarkSquirrel42

Reputation: 10257

you could change (or overload) the ActionMethods signature to take a string Parameter

like...

public ActionResult Message(String someVariable)
    {
        //do something with the contents of someVariable
        chartstype chartname = new chartstype();
        List<chartstype> listchart = new List<chartstype>();
        chartname.charttype = "Column";
        listchart.Add(chartname);
        TempData["name"] =listchart;
        TempData.Keep();
        return View();
    }

which could be called like https://www.example.com/Message?someVariable=someString

Upvotes: 1

Related Questions