如何将返回类型更改为“字符串”并仅返回视图名称

时间:2018-11-29 16:55:34

标签: c# asp.net asp.net-mvc

我有一个帮助器类,在其中检查某些条件,如果是真的,请返回viewpage1,否则返回viewpage2。

在if / else语句中,我使用了HttpContext.Current.Response.Redirect来重定向用户。但是,该方法期望返回一个模型。如果在方法中间进行重定向,将永远不会返回任何结果。相反,我认为需要将返回类型更改为“字符串”,然后仅返回视图名称。我该怎么办?

助手类:

    public static OperationResult RetrievemData(customerViewModel model)
    {
        try
        {
            var sqlStatement = @"select * from customertable where last_name=@last_name ";
            using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DB_LIB_CONNECTION_STRING"].ConnectionString))
            {
                connection.Open();
                using (var sqlCommand = new SqlCommand(sqlStatement, connection))
                {
                    sqlCommand.Parameters.Add("@last_name", SqlDbType.VarChar).Value = model.LastName;
                    using (var sqlResult = sqlCommand.ExecuteReader())
                    {
                        if (sqlResult.HasRows)
                        {
                            HttpContext.Current.Response.Redirect("~/ViewPage1");

                        }
                        else
                        {
                            HttpContext.Current.Response.Redirect("~/ViewPage2");
                        }
                    }
                }
            }
        }
        catch (Exception e)
        {
            throw new Exception("An error was encountered. " + e);
        }

        return model;
    }

控制器:

        [HttpPost]
    public ActionResult Getdata(customerViewModel model)
    {
        if (!ModelState.IsValid)
            return View(model);

        var keyvalue = Convert.ToInt64(HttpContext.Session["Appkey"]);
        long temp;
        bool success = Int64.TryParse((HttpContext.Request.QueryString["keyvalue"]), out temp);
        if (success)
        {
            return View(CustomerViewHelper.RetrievemData(model));

        }
        else
        {
            return View(CustomerViewHelper.SpecificData(keyvalue));
        }
    }

1 个答案:

答案 0 :(得分:0)

public static string RetrievemData(customerViewModel model)
{
    try
    {
        var sqlStatement = @"select * from customertable where last_name=@last_name ";
        using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["DB_LIB_CONNECTION_STRING"].ConnectionString))
        {
            connection.Open();
            using (var sqlCommand = new SqlCommand(sqlStatement, connection))
            {
                sqlCommand.Parameters.Add("@last_name", SqlDbType.VarChar).Value = model.LastName;
                using (var sqlResult = sqlCommand.ExecuteReader())
                {
                    return sqlResult.HasRows ? "~/ViewPage1" : "~/ViewPage2";
                }
            }
        }
    }
    catch (Exception e)
    {
        throw new Exception("An error was encountered. " + e);
    }
}