2012-07-26 41 views
0

我想从视图强制类型传递给控制器​​。我的观点是强烈的类型。不知何故,当控制器中调用“Save”操作方法时,我在属性值中获得“null”。我正在使用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; } 
    } 
} 

回答

1

ActionLinks唐不要提交表格。变化:

@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"; 
    } 
+0

是否有产生Submit按钮任何辅助方法? – Asdfg 2012-07-26 16:38:22

+0

不,但是可能有很多创建自己的帮手来做这件事的例子。 – 2012-07-26 16:39:56

1

ActionLink辅助方法呈现作为链接的锚标记。它不会提交表格。 Erik提到您需要在表单中提交按钮。

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

<script type="text/javascript"> 

    $(function(){ 
     $("#Save").click(function(){ 
     $(this).closest("form").submit();   
     }); 
    }); 

</script> 
相关问题