我是ASP.NET MVC的新學習者。這個問題應該很容易回答專業。我試圖提交表單(發表評論),並獲得錯誤。無法解析ASP.NET MVC錯誤
這裏是我的控制器
[HttpPost]
public ActionResult Index(long id, CommentViewModel comment) {
var service = new UserService();
var articleService = new ArticleService();
comment.UserId = service.GetUserByUsername(User.Identity.Name).UserId;
comment.ArticleId = id;
comment.CommentTime = DateTime.Now;
articleService.AddArticleComment(comment);
return View();
}
這裏是我的ViewModel
public class CommentViewModel : BaseViewModel {
public Int64 CommentId { get; set; }
public Int64 UserId { get; set; }
public Int64 ArticleId { get; set; }
public DateTime CommentTime { get; set; }
public String CommentBody { get; set; }
}
這裏是我的看法(HTML)
<form class="form-stacked" id="comment-form" action="@Url.Action("Index", "Article")" method="post" enctype="multipart/form-data">
<label class="control-label" for="commentTextArea">Leave a comment...</label>
<textarea rows="3" id="commentTextArea" name="commentBody" class="span8"></textarea>
<input type="submit" value="Post Comment" />
</form>
這是URL
http://localhost:58856/Article?Id=1
,這是錯誤消息
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int64' for method 'System.Web.Mvc.ActionResult Index(Int64, TechCells.Services.ViewModels.CommentViewModel)' in 'TechCells.Web.UI.Controllers.ArticleController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
Parameter name: parameters
我想MVC會自動檢測從URL id
,並自動分配基於名字的ViewModel屬性。對?
這個錯誤的原因是什麼?我該如何解決?
謝謝。
你的路由註冊碼是什麼樣的? – Jasen
@Jasen,它只有默認的路由註冊。 routes.MapRoute( 名: 「TcMainRoute」, URL: 「{控制器}/{行動}」, 的默認值:新的{ 控制器= 「主頁」, 行動= 「索引」, }); – Zafar