简体   繁体   English

从视图调用控制器动作

[英]Call a controller action from view

I am trying to call an action from the controller using onclick method. 我正在尝试使用onclick方法从控制器调用操作。 For some reason it's not returning action I want, it's always jumping to public ActionResult Index() by default. 由于某些原因,它没有返回我想要的操作,因此默认情况下始终会跳转到public ActionResult Index()

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Register" class="btn btn-default" onclick="location.href='@Url.Action("RegisterIndex", "Register")'"/>
        </div>
    </div>

NOTE 注意

I have created view automatically with a model. 我已经使用模型自动创建了视图。 It's validating input for me by using already generated javascripts. 它通过使用已经生成的javascripts为我验证输入。 If I change input tag to button it's not gonna do the required validation. 如果我将输入标签更改为按钮,则无法进行所需的验证。

window.location.href does a GET request, that's why it didn't pass your input values to the server. window.location.href发出GET请求,这就是为什么它没有将输入值传递到服务器。

When you have <input type="submit"> inside a form, clicking it will submit the form with all data you need. 当您在表单中包含<input type="submit"> ,单击该表单将提交包含所需所有数据的表单。 I think this is what you want, but you just want it to submit to another action . 我认为这是您想要的,但是您只是希望它提交给另一个action

To achieve this, I suggest this solution: 为此,我建议采用以下解决方案:

  1. Create a hidden field in the form. 在窗体中创建一个hidden字段。 Its data will be sent to the server. 它的数据将被发送到服务器。
  2. In your server, base on that hidden value, you can redirect to the appropriate action 在服务器中,基于该hidden值,您可以redirect到适当的action

Please feel free to ask me if you find anything unclear :) 如果您有任何不清楚的地方,请随时问我:)

The <input type="submit"> , when inside a form element, will submit the form when clicked unless you return false or event.preventDefault(); 除非您返回false或event.preventDefault();否则<input type="submit"> (在表单元素内)将在单击时提交表单event.preventDefault();

returning false will prevent the default behavior for your submit. 返回false将阻止您的提交的默认行为。

EDIT 编辑

window.location.href will cause a GET request so your data will not be posted using this method. window.location.href将导致GET请求,因此不会使用此方法发布您的数据。

HTML 的HTML

     @using (Html.BeginForm())
  {
      <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit"  id="btnSubmit" value="Register" class="btn btn-default"/>
        </div>
    </div>
  }

Javascript Java脚本

  <script>
    $(document).ready(function () {
        $("#btnSubmit").click(function () { window.location.href = '@Url.Action("RegisterIndex", "Register")'; return false; });
    });
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM