在ASP.NET MVC中的Post请求上执行代码

时间:2015-03-20 13:47:35

标签: c# asp.net asp.net-mvc razor razor-2

我是ASP.NET MVC的新手,并且想知道如何执行以下操作:

我有一个包含这样一些按钮的列表:

@model List<SitefinityWebApp.Mvc.Models.ProfileModel>

@using (Html.BeginForm())
{
   <ul>
      @foreach (var item in Model)
      {
         <li>
            <span>@item.EmailAddress</span>
            <button id="submit">Generate code</button>
        </li>
      }
   </ul>
}

因此,当用户点击该按钮时,我需要在服务器上执行一些代码,我需要将电子邮件地址作为参数。

我想我需要一个POST,但我不知道如何设置它。最后,我希望再次呈现相同的列表。

我尝试了一个ActionLink,但这只是我理解的GET请求吗?

关于如何做到这一点的任何想法?

谢谢, 丹尼尔

2 个答案:

答案 0 :(得分:3)

您可以在Controller中定义POST功能。与GET呼叫同名。
你的Get Call应该喜欢这样的东西:

public ActionResult Index()
{
    List<ProfileModel> list = new List<ProfileModel>();
    list.add(listItem);

    return View(list);
}

然后制作POST功能:

[HttpPost]
public ActionResult Index(List<ProfileModel> postModel)
{
    var emailAddress = postModel.EmailAddress
    // do some stuff here

    return RedirectToAction("Index");
}

您可以使用Html.BeginForm中的参数调用任何POST函数:

@using (Html.BeginForm("MothodeName", "ControllerName", FormMethod.Post))
{
<!-- form here -->
}

答案 1 :(得分:0)

目前还不完全清楚你想做什么。目前您正在单个表单中呈现多个按钮,但表单没有控件,因此不会回发任何内容(并且由于您未指定按钮type属性,因此根据浏览器的不同,它可能无法触发提交)。解决此问题的一种方法是为每个回发电子邮件地址的项目提供一个表单(指定路由参数),然后重定向回索引页面。

@foreach (var item in Model)
{
  <span>@item.EmailAddress</span>
  @using (Html.BeginForm("ProcessEmail", new { emailAddress = item.EmailAddress }))
  {
    <button type="submit">Generate code</button>
  }
}

,POST方法将是

[HttpPost]
public ActionResult ProcessEmail(string emailAddress)
{
  // do something with the email
  return RedirectToAction("Index"); // redisplay the page
}

或者,您可以使用隐藏输入而不是路径参数

@foreach (var item in Model)
{
  <span>@item.EmailAddress</span>
  @using (Html.BeginForm("ProcessEmail"))
  {
    @Html.HiddenFor(m => item.EmailAddress , new { id = "" }) // remove the id attribute to prevent invalid html
    <button type="submit">Generate code</button>
  }
}

但是,为了获得更好的性能并避免每次都重新生成视图,您可以使用ajax发布值

@foreach (var item in Model)
{
  <span>@item.EmailAddress</span>
  <button type="button" class="process-email" data-email="@item.EmailAddress">Generate code</button>
}

var url = '@Url.Action("ProcessEmail")';
$('.process-email').click(function() {
  $.post(url, { emailAddress: $(this).data('email') }, function(response) {
    if(response) {
      // processing succeeded - display message?
    } else {
      // processing failed = display error?
    }
  })
})

并将方法修改为

[HttpPost]
public JsonResult ProcessEmail(string emailAddress)
{
  // do something with the email
  return Json(true); // or return Json(null) if an error occured
}