如何在MVC5中调用HttpPost ActionResult



我的应用程序中有一个联系人视图,它包含一个表单,定义如下:

<form role="form" style="width:100%; float:left;">
    <div class="form-group">
        <a href="#"><img src="~/Content/img/zarf.png" class="zarf-pos"></a>
    </div>
    <div class="form-group">
        <label for="exampleInputEmail1">Name and Surname</label>
        <input type="text" name="fullName" class="form-control" id="exampleInputEmail1" placeholder="Enter your full name" required>
    </div>
    <div class="form-group">
        <label for="exampleInputPassword1">E-Mail</label>
        <input type="email" name="emailAddress" class="form-control" id="exampleInputPassword1" placeholder="Enter your e-mail address" required>
    </div>
    <div class="form-group">
        <label for="exampleInputEmail1">Write to us</label><br>
        <textarea name="message" class="form-control" rows="5" placeholder="How can we help you?" required></textarea>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-default reg-position">Send</button>
    </div>
</form>

然后,在我的控制器中,我有两个ActionResults,一个HttpGet和一个HttpPost,定义如下:

[HttpGet]
public ActionResult Contact()
{
    return View();
}
[HttpPost]
public ActionResult Contact(string fullName, string emailAddress, string message)
{  // some functionality }

但是,当我填写表格并单击"发送"按钮时,它会重定向到空的"联系人"页面。重点是我需要两个Contact方法,而在Post方法中,我有一些代码假设字符串不是空的。如果我只有一个联系人方法,我会收到一条错误消息,说字符串为null,并且视图不会显示。所以,我决定有两个方法,但不知道按下按钮时如何调用post方法。

假设您正在使用Razor创建视图,则定义如下形式:

@using( Html.BeginForm() )
{
    <div class="form-group">
        <a href="#"><img src="~/Content/img/zarf.png" class="zarf-pos"></a>
    </div>
    <div class="form-group">
        <label for="exampleInputEmail1">Name and Surname</label>
        <input type="text" name="fullName" class="form-control" id="exampleInputEmail1" placeholder="Enter your full name" required>
    </div>
    <div class="form-group">
        <label for="exampleInputPassword1">E-Mail</label>
        <input type="email" name="emailAddress" class="form-control" id="exampleInputPassword1" placeholder="Enter your e-mail address" required>
    </div>
    <div class="form-group">
        <label for="exampleInputEmail1">Write to us</label><br>
        <textarea name="message" class="form-control" rows="5" placeholder="How can we help you?" required></textarea>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-default reg-position">Send</button>
    </div>
}

这将确保生成正确的<form>元素以发布回您的操作。

附言:只是一些术语整理。。。您不调用ActionResult,而是调用Actions,它们返回ActionResults。当你与其他开发人员交谈时,如果你使用了正确的名称,这将有所帮助。

最新更新