开发者

asp.net MVC ActionMethod causing null exception on parameter

开发者 https://www.devze.com 2022-12-22 14:11 出处:网络
I am trying to add filter functionality that sends a GET request to the same pageto filter records in my table.

I am trying to add filter functionality that sends a GET request to the same page to filter records in my table.

The problem I am having is that the textbox complains about null object reference when a parameter is not passed. For example, when the person first views the page the url is '/mycontroller/myaction/'. Then when they apply a filter and submit the form it should be something like 'mycontroller/myaction?name=...'

Obviously the problem stems from when the name value has not been passed (null) it is still trying to be bound to the 'name' textbox. Any suggestions on what I should do regarding this problem?

UPDATE I have tried setting the DefaultValue attribute but I am assuming this is only for route values and not query string values ActionResult MyAction([DefaultValue("")] string name)

//Action - /mycontroler/myaction
ActionResult MyAction(string name)
{
    ...do stuff
}开发者_JAVA技巧

//View
<div id="filter">
    <% Html.BeginForm("myaction", "mycontroller", FormMethod.Get); %>
    Name: <%= Html.TextBox("name") %>
    ....
</div>
<table>...my list of filtered data


Decided to implement this differently so that the input box posted to a different action method which did some business logic work and then redirected back to the original page.

POST-REDIRECT-GET


//Action - /mycontroler/myaction
ActionResult MyAction(string name)
{
    if (name == null) {
        name = string.Empty;
    }
    ...do stuff
}

Or... add an overload...

//Action - /mycontroler/myaction
ActionResult MyAction()
{
     return MyAction(string.Empty);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消