2012-07-26 42 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> 
相關問題