Object reference not set to instance of an object while getting data from request object/Formcollection

只愿长相守 提交于 2019-12-31 03:02:29

问题


i am trying to implement a simple add operation using MVC Ajax

My code is as follows:

Public Class Model

{
  public int number1{get;set;}

  public int number2{get;set;}

}


[HttpPost]
public string TestAjax( )
{
  int strnum1 = Convert.ToInt32(Request["txtbox1"].ToString());
  int strnum2 = Convert.ToInt32(Request["txtbox2"].ToString());
  string strnum3 = Convert.ToString(strnum1 + strnum2);
  if (strnum3 != null)
  {
     return strnum3;
  }  
  return string.Empty;   
}

It is hitting the Ajax action method. But, i was not able to fetch the values from the request object or from the form collection

I am getting , object reference not set to instance of an object error message.

Updated: Client Side Code

  <% using (Ajax.BeginForm("TestAjax", "Reviewer", new AjaxOptions { UpdateTargetId = "textEntered" }))
       { %>
    <table align="center">
        <tr>
            <td class="tdCol1Align">
                <label>
                    Number1</label>
            </td>
            <td class="tdCol2Align">
                <input type="text" id="txtbox1" />
            </td>
        </tr>
        <tr>
            <td class="tdCol1Align">
                <label>
                    Number2</label>
            </td>
            <td class="tdCol2Align">
                <input type="text" id="txtbox2" />
            </td>
        </tr>
        <tr>
            <td colspan="2" align="center">
                <input type="submit" value="Add" class="button" />
            </td>
        </tr>
    </table>
    <%
        }
    %>
    <br />
    <br />
    <span id="textEntered"></span>

Please help..


回答1:


You need to set the name attribute in your html element:

<input type="text" id="txtbox2" name="txtbox2" />



回答2:


Update: Based on your model:

[HttpPost]
public int TestAjax(Model mymodel)
{
  return mymodel.number1 + mymodel.number2;
}

And in your HTML assuming you are referencing the model:

@model Model

replace your inputs with this accordingly:

@Html.TextBoxFor(model => model.number1)
@Html.TextBoxFor(model => model.number2)

You have to validate that the user only types integer valid values in your textboxes with javascript.



来源:https://stackoverflow.com/questions/19536709/object-reference-not-set-to-instance-of-an-object-while-getting-data-from-reques

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