Object reference not set to instance of an object

2019-02-27 07:14发布

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..

2条回答
Bombasti
2楼-- · 2019-02-27 07:58

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.

查看更多
Explosion°爆炸
3楼-- · 2019-02-27 08:08

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

<input type="text" id="txtbox2" name="txtbox2" />
查看更多
登录 后发表回答