2017-03-27 42 views
-5

我有下面的代码,其将从用户接受的值和这些值需要被传递到控制器。我可以使用动作链接,但我想知道request.input变量是如何工作的。通值抛出错误

@using (Html.BeginForm("LoginResult", "Dashboard", FormMethod.Post)) 
{ 

@Html.EditorFor(model =>model.username) 

在控制器:

public ActionResult LoginResult() 
    { 
     string strName = Request["username"].ToString();   
     return View(); 
    } 

和模型

public class Employee 
    { 

      public string username { get; set; } 
      public string age { get; set; } 

    } 

,但得到的错误

型 'System.NullReferenceException' 的异常出现在 MvcApplication5.dll但是是OT在用户代码来处理

其他信息:对象引用不设置到 对象的实例。

+0

一旦您提交表单,这些值会回传给控制器。如果有行动链接,您将通过点击提交表单或通过Ajax发布数据。 – Saravanan

+1

避免在控制器中使用'Request'。试着坚持让框架做对你的工作,让模型绑定绑定到参数等 – mason

+2

[几乎所有的你的代码是不是在MVC框架/样式做(https://www.asp.net/ mvc/overview/getting-started)...我强烈建议你实际制作模型(MVC =模型视图控制器),使用EditorFor等。否则使用MVC确实没有意义,你可以使用[WebPages](https ://www.asp.net/web-pages)。 –

回答

2

这里是你将如何处理这个

<body> 
    <h2>Dashboard</h2> 
    <form method="post" action="" > 
    <table> 
     <tbody> 
      <tr> 
       <td> 
        <input type="text" id="textname" name="txtname" /> 
       </td> 
       <td> 
        <input type="text" id="textpassword" name="textpassword" /> 
       </td> 
       <td> 
        <input type="button" id="btnclickhere" name="btnclickhere" value="ClickHere" /> 
       </td> 
      </tr> 
      <tr><td>**<input type="submit" value="Save" />**</td></tr> 
     </tbody>   
    </table> 
    </form> 

否则,你将有看起来像下面

<a href="javascript:void()" onclick="doLogin()" >Login</a> 

<script type="text/javascript"> 
function doLogin(){ 
var postData = { 
     username = $("#textname").val(), 
     password = $("#textpassword").val 
}; 
$.ajax({ 
    type: "POST", 
    url: '/account/logon', 
    data: JSON.stringify(postData), 
    success: function(result){ 
}, 
    contentType:"application/json", 
    dataType: "json" 
}); 
} 
</script> 

我想建议你,你更好的岗位的链接表单并不使用ajax中的值。另外,为了更好的安全性,请将该页面放在HTTPS站点上。

希望这会有帮助

+0

谢谢saravanan。我已经更新了你的答案中显示的代码,但仍然会得到同样的错误。我更新了我的问题中的代码。你能告诉我哪里出了问题吗? –