如何在mvc中从viewpage传递参数到控制器

时间:2018-03-26 00:59:07

标签: asp.net-mvc asp.net-mvc-4

请帮帮我。 我无法将输入参数从textbox绑定到actionmethod

控制器代码:

public ActionResult CheckUser(string empCode)   // ActionMethod with parameter
{
    try
    {
        string res = "";
        DataSet dataSet = new DataSet();
        using (SqlConnection connection = new SqlConnection(ConnectionString))
        {
            using (SqlCommand command = new SqlCommand("spUserCheck"))
            {
                command.Parameters.AddWithValue("@UserCode", empCode);
                command.CommandType = CommandType.StoredProcedure;
                connection.Open();
                command.Connection = connection;
                SqlDataAdapter dataAdapter = new SqlDataAdapter();
                dataAdapter.SelectCommand = command;
                dataAdapter.Fill(dataSet);
                connection.Close();
            }
        }
        if (dataSet.Tables.Count > 0)
        {
               res = "Alredy Avilable";
        }
        else
        {
            res = "Not Avilable. Please create user";                        
        }
        return View(res) ;
    }
    catch (Exception ex)
    {
        throw new Exception("Error ", ex);
    }
}

ViewCode: -

<div class="form-group">
    <label class="control-label col-sm-2">Employee Code <span class="mandatory"></span>:</label>
    <div class="col-sm-3">
        <input type="text" class="form-control input-md" id="empCode" placeholder="Enter employee code" />
    </div>
    <div class="col-sm-2">
        <input type="button" class="btn btn-info" onclick="location.href='@Url.Action("CheckUser", "User")'" id="btnAvaiaable" value="Check Availability ?" />
    </div>
</div>

ModelCode

public class UserParameter
{
    public string empCode { get; set; }
    public string Role { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string EmailID { get; set; }
    public int MobileNo { get; set; }
    public string Zone { get; set; }
    public string State { get; set; }
    public string Branch { get; set; }
    public string CompanyType { get; set; }
}

1 个答案:

答案 0 :(得分:1)

第一个问题是您需要一个属性为name="empCode"的文本框。

其次,您需要将文本框包装在表单元素中。

第三,您需要发布到控制器。只需在按钮点击中更改位置(正如您所做的那样)将执行get而不附加任何表单数据。

网上有很多样本可以证明这一点。