MVC 4 Page not working after altering Html.beginform()

与世无争的帅哥 提交于 2019-12-25 03:54:16

问题


I had been using this line at the top of my edit.cshtml page:

@using (Html.BeginForm())

but then I changed it to:

@using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))

and now when I hit submit on that page I try to run this method:

public ActionResult Edit([Bind(Include = "description,tags,files,fileString")] Task task, int keyId, string editFiles)

I get this error:

The parameters dictionary contains a null entry for parameter 'keyId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Combined.Models.Task, Int32, System.String)' in 'Combined.Controllers.HomeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.ArgumentException: The parameters dictionary contains a null entry for parameter 'keyId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Combined.Models.Task, Int32, System.String)' in 'Combined.Controllers.HomeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

I tried changing the line to:

@using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { enctype = "multipart/form-data", keyId = Model.keyId }))

but it didn't make any difference. What am I doing wrong?


回答1:


Add KeyId to the form as a hidden input instead of in the route parameters, since you are posting.

@Html.HiddenFor(model => model.keyId)

(Actually, you are adding it as an Html Attribute. View source on your page and look where it is being rendered.)




回答2:


Thanks @ehsan-sajjad, in my case I was using the wrong overload and your comment helped me.

This is what worked, putting the id after the controller and before the form method:

@using (Html.BeginForm("Edit", "Home", new { keyId = Model.keyId }, FormMethod.Post))


来源:https://stackoverflow.com/questions/25188448/mvc-4-page-not-working-after-altering-html-beginform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!