【问题标题】:Update and ASP.NET MVC model on button click单击按钮时更新和 ASP.NET MVC 模型
【发布时间】:2015-01-27 15:54:14
【问题描述】:

我是 ASP.NET MVC 的新手。我试图在按钮单击时更新模型但没有成功:每次按下按钮时都会调用一个 HttpGet 控制器方法。

这是我的标记

@model DataInterface.Model.Entry

<button onclick="location.href='@Url.Action("Survey")'">Finish survey</button>

这是控制器代码

[HttpGet]
public ActionResult Survey()
{
    var entry = new Entry();
    return View(entry);
}

[HttpPost]
public ActionResult Survey(Entry newEntry)
{
       // save newEntry to database
}

当我单击按钮时,会调用 HttpGet 方法。为什么?


当菜鸟不好) 谢谢大家!

【问题讨论】:

  • 嗯,这正是您告诉浏览器要做的事情。单击按钮时,浏览器的 URL 将更改为指向控制器中的 Survey 方法。浏览器将向它发送一个获取请求并处理响应。发送POST 请求的最简单方法是提交表单。

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


【解决方案1】:

如果您访问URL 而不明确指定HTTP methodASP.NET MVC 将假定GET 请求。要更改这一点,您可以添加一个表单并发送它:

@using (Html.BeginForm("Survey", "Controller", FormMethod.Post))
{
    <input type="submit" value="Finish survey" />    
}

如果您这样做,您的POST 方法将被调用。但是,Entry 参数将为空,因为您没有指定要随请求一起发送的任何值。最简单的方法是指定输入字段,例如文本输入、下拉菜单、复选框等。

@using (Html.BeginForm("Survey", "Controller", FormMethod.Post))
{
    @Html.TextBoxFor(m => m.Title)
    <input type="submit" value="Finish survey" />    
}

如果您将对象存储在服务器上的某个位置,并且只想通过将其写入数据库或更改其状态来完成它,您可以在帖子中传递对象的Id(或一些临时 ID)请求并使控制器方法仅适用于 Id:

@using (Html.BeginForm("Survey", "Controller", FormMethod.Post))
{
    @Html.HiddenFor(m => m.Id)
    <input type="submit" value="Finish survey" />    
}

[HttpPost]
public ActionResult Survey(Entry newEntry)
{
    // newEntry.Id will be set here
}

【讨论】:

  • 旁注:由于视图是由Survey() 方法生成的,所以只需要@using (Html.BeginForm()) {... - 如果您想覆盖默认值,只需包含参数
【解决方案2】:
   @using (Html.BeginForm("Survey", "<ControllerName>", FormMethod.Post))
   {
       <input  type="submit" value="Finish survey" />    
   }

【讨论】:

    【解决方案3】:

    你必须声明你的表格

    @model DataInterface.Model.Entry
    @using (Html.BeginForm("action", "Controlleur", FormMethod.Post, new {@class = "form", id = "RequestForm" }))
    {
    <input  type="submit" value="Finish survey" />
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-24
      • 2013-03-01
      • 2017-03-06
      • 2011-06-16
      • 1970-01-01
      • 2023-02-17
      • 1970-01-01
      • 1970-01-01
      • 2012-05-13
      相关资源
      最近更新 更多