【问题标题】:passing model to controller sends null将模型传递给控制器​​发送 null
【发布时间】:2012-07-27 00:48:04
【问题描述】:

我正在尝试将我的模型从视图传递到控制器的强类型。我的观点是强类型的。当在控制器中调用“保存”操作方法时,我以某种方式在属性值中获取“空”。我正在使用Asp.Net MVC 3

这就是我的视图的样子:

@model MvcApplication2.Models.Event
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <title>AddNew</title>
</head>
<body>
    @using(Html.BeginForm("Save","Event",FormMethod.Post, Model))
    {
        <div>
            <p>@Html.LabelFor(m=>m.EventName) @Html.TextBoxFor(m=>m.EventName)</p>
            <p>@Html.LabelFor(m=>m.Venue) @Html.TextBoxFor(m=>m.Venue)</p>
            <p>@Html.LabelFor(m=>m.StartTime) @Html.TextBoxFor(m=>m.StartTime)</p>
            <p>@Html.LabelFor(m=>m.EndTime) @Html.TextBoxFor(m=>m.EndTime)</p>
            @Html.ActionLink("Save Event", "Save")
        </div>
        }
</body>
</html>

这就是我的EventController 的样子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;

namespace MvcApplication2.Controllers
{
    public class EventController : Controller
    {

        public string Save(Event eventModel)
        {
           //Here eventModel.EventName and rest of the properties are null.

            return "Saved";
        }

    }
}

这是模型的样子:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace MvcApplication2.Models
{
    public class Event
    {
        public string EventName { get; set; }
        public string Venue { get; set; }
        public string StartTime { get; set; }
        public string EndTime { get; set; }
    }
}

【问题讨论】:

    标签: asp.net-mvc-3 razor controller


    【解决方案1】:

    ActionLink 不提交表单。变化:

    @Html.ActionLink("Save Event", "Save")
    

    <input type="submit" value="Save">
    

    此外,如果您将 [HttpPost] 添加到您的方法中,这会更加明显。

        [HttpPost]
        public string Save(Event eventModel)
        {
           //Here eventModel.EventName and rest of the properties are null.
    
            return "Saved";
        }
    

    【讨论】:

    • 有生成提交按钮的Helper方法吗?
    • 不,但是可能有很多例子可以创建你自己的助手来做到这一点。
    【解决方案2】:

    ActionLink 辅助方法渲染一个锚标记,它是一个链接。它不会提交表单。正如 Erik 所说,您需要在表单中添加一个提交按钮。

    如果您仍想保留链接而不是提交按钮,您可以使用一些 javascript 代码来提交表单

    <script type="text/javascript"> 
    
        $(function(){
          $("#Save").click(function(){
             $(this).closest("form").submit();        
          });
        });
    
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-08
      • 2022-01-25
      • 1970-01-01
      • 2011-07-03
      • 2016-06-02
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多