【问题标题】:identify which button is being clicked in mvc 5确定在 mvc 5 中单击了哪个按钮
【发布时间】:2017-10-02 09:01:05
【问题描述】:

我正在使用 mvc 5 创建一个 Web 应用程序,这里有两个按钮

<div class="row">
    <div class="col-sm-offset-5 col-sm-1">
        <input type="submit" name="save" value="SAVE" class="btn btn-primary glyphicon glyphicon-save" />
    </div>
    <div class="col-sm-offset-0 col-sm-1">

            <input type="submit" name="reset" id="reset" value="Reset" class="btn btn-warning active glyphicon glyphicon-refresh" />
    </div>                        
</div>

我有一个方法,在点击按钮后被调用,

现在在那个事件上我想区分按钮点击,

喜欢,

如果用户点击

<input type="submit" name="save" value="SAVE" class="btn btn-primary glyphicon glyphicon-save" />

然后

{
//this code should run
}

如果用户点击

<input type="submit" name="reset" id="reset" value="Reset" class="btn btn-warning active glyphicon glyphicon-refresh" />

然后

{ //this set of code should run }

我的方法是这样的

[HttpPost]
        public ActionResult insertrecd(FormCollection fc)
        { 
            if(fc["reset"]==null)
            {
                return RedirectToAction("party", "party");
            }
            else
            {
                ViewBag.message = string.Format("Hello {0}.\\nCurrent Date and Time: {1}", "name", DateTime.Now.ToString());
                return RedirectToAction("party", "party");
            }
        }

我需要做什么,我想在不同的按钮点击上做不同的代码?

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-5


    【解决方案1】:

    为每个输入按钮赋予相同的名称,但值不同

    <input type="submit" name="action" value="save" class="btn btn-primary glyphicon glyphicon-save" />
    
    <input type="submit" name="action" id="reset" value="reset" class="btn btn-warning active glyphicon glyphicon-refresh" />
    

    然后该值将作为

    出现在您的表单集合中
    fc["action"]
    

    所以你的控制器动作可能看起来像

    [HttpPost]
    public ActionResult insertrecd(FormCollection fc)
    {
        var action = fc["action"];
    
        if(action == "save")
        {
            //save stuff
        }
    
        if(action =="reset")
        {
            //reset stuff
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多