如何将字符串从View传递给Controller

时间:2017-09-04 11:45:02

标签: c# asp.net-mvc

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();
}

我想更改我的代码,以便能够将字符串传递给View中的chartname.charttype变量。

3 个答案:

答案 0 :(得分:1)

您可以更改(或重载)ActionMethods签名以获取字符串参数

像...

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();
    }

可以像https://www.example.com/Message?someVariable=someString

一样调用

答案 1 :(得分:0)

在控制器中

        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();
        }

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

答案 2 :(得分:0)

   public ActionResult Message(string message)

并确保查看string是否为null,因为任何人都可以通过url调用此方法。

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

然后在视图中编码

<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"/>

如果您不想看到文本框,请使用

<input type="hidden" name="message" value="somevalue"/> 除非你想使用ajax从javaScript调用你的方法?