3

I am trying to build simnple search utility searching my Employees by last Name.

Here is my Razor View

    @using(Html.BeginForm("Index","Employee", FormMethod.Post))
{
    <p>
        Search employees by Last Name : @Html.TextBox("SearchString")
        <input type="submit" value="Submit" name="Search" />     
    </p>
}

Here is my Controller

        // GET: /Employee/
    public ActionResult Index(string lastName)
    {
        var employees = db.Employees;
        if (!String.IsNullOrEmpty(lastName))
        {
            employees = employees.Where(p => p.LastName.ToUpper().Contains(lastName.ToUpper()));
        }            
        return View(employees.ToList());
    }

Debugging shows the Submit button posting back to the index method, but the value lastName returned to the Index method is always null. How can I pass the lastName correctly?

1

2 Answers 2

3

your @Html.TextBox("SearchString") name and action method parameter name must match. (SearchString)

[HttpPost]
public ActionResult Index(string SearchString)
{
    var employees = db.Employees;
    if (!String.IsNullOrEmpty(SearchString))
    {
        employees = employees.Where(p => p.LastName.ToUpper().Contains(SearchString.ToUpper()));
    }            
    return View(employees.ToList());
}
Sign up to request clarification or add additional context in comments.

Comments

0

You must name the variable in your ActionResult the same as the field name so in your example, either set the TextBox value to lastName or name the variable in the ActionResult Index to SearchString

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.