【问题标题】:Submit button action in MVC controller在 MVC 控制器中提交按钮操作
【发布时间】:2019-07-22 14:42:22
【问题描述】:

我正在尝试找出在控制器中创建提交和添加按钮操作的最佳方法。

我有一个用于创建(提交)的 HttpGet,但不确定如何执行 HttpPost 或者是否需要 Get 或 Post:

[HttpGet]
public IActionResult Create()
{
    var drafList = _drService.GetDraft().ToList();

    var IndexViewModel = new IndexViewModel();
    IndexViewModel.Draft = draftList;
    IndexViewModel.Published = _drService.GetPublished();
    IndexViewModel.Current = _drService.GetCurrent();

    return View(IndexViewModel);
}
<div class="row">
    <div class="col-md-4">
        <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text- danger"></div>
            <div class="form-group">
                <div class="col-md-3">
                    <label for="asof">As of:</label>
                </div>
                <div class="col-md-9">
                    <input name="AsOf" type="date" title="AsOf" class="form-control" />
                </div>
            </div>
            <div class="clearfix col-md-12"></div>
            <div class="clearfix col-md-12"></div>
            <div class="form-group">
                <div class="col-md-2">
                    <label for="title">Title:</label>
                </div>
                <div class="col-md-9 col-md-offset-1">
                    <input type="text" class="form-control" id="title" />
                </div>
                <div class="col-md-6">
                    <input type="submit" value="Add" class="btn btn-primary" />
                </div>
            </div>
        </form>
    </div>
</div>

我希望在单击“添加”按钮时执行控制器中的操作并添加记录。

【问题讨论】:

标签: asp.net-core model-view-controller


【解决方案1】:

我认为您可以创建一个具有相同名称的控制器操作(在本例中为 create()),但在操作上使用 [httpPost] 前缀,以便表单在提交时调用 post create 操作

【讨论】:

    【解决方案2】:

    GET 用于非破坏性操作,即相同的 GET 请求在重复时应该返回相同的响应。对于创建,您需要使用 POST。基本上,您需要添加如下操作:

    [HttpPost]
    public async Task<IActionResult> Create(IndexViewModel model)
    {
        if (!ModelState.IsValid)
            return View(model);
    
        // map the data posted (`model`) onto your entity class
        var entity = new MyEntity
        {
            Foo = model.Foo,
            Bar = model.Bar
        };
    
        _context.Add(entity);
        await _context.SaveChangesAsync();
        return RedirectToAction("Index");
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-11
      • 2016-10-22
      • 2018-07-18
      • 2012-07-10
      • 2015-04-16
      • 1970-01-01
      • 1970-01-01
      • 2013-07-13
      相关资源
      最近更新 更多