【问题标题】:Pass a string value as parameter in Url.action在 Url.action 中将字符串值作为参数传递
【发布时间】:2015-07-31 11:17:51
【问题描述】:

我正在使用asp.net mvc 4EF6 开发一个网站。我想在Url.action 链接中将字符串值作为参数传递。但是,每当我点击链接时,我都会收到此错误:

参数类型“Edm.Int32”和“Edm.String”不兼容此操作。在 WHERE 谓词附近,第 1 行,第 76 列。

这是创建它的代码:

控制器

public ActionResult Edit(string EditId)
{
    if (Session["username"] != null)
    {
        UserInfo uinfo = db.UserInfoes.Find(EditId);
        return View(uinfo);
    }
    else
    {
        return RedirectToAction("HomeIndex");
    }
}

查看

<a class="btn btn-info" 
 href="@Url.Action("Edit", "Home", new { EditId = item.regno.ToString() })"><b>Edit</b></a>

如何使用字符串值作为参数?

【问题讨论】:

  • item.regno 是整数吗?
  • 不,它是一个 varchar。
  • 你的实体UserInfo的主键是什么数据类型?
  • 问题不在于操作链接,而是您将 varchar 传递给 .Find() 方法作为搜索键,而它需要一个整数。
  • Tnx。那么我应该使用什么来代替.Find()

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


【解决方案1】:
public ActionResult Edit(string EditId)
    {
        if (Session["username"] != null)
        {
            int id;
            //Check try to parse the string into an int if it fails it will return false if it was parsed it will return true
            bool result = Int32.TryParse(EditId, out id);
            if (result)
            {                    
                 //I wouldn't use find unless you're 100% sure that record will always be there.
                 //This will return null if it cannot find your userinfo with that ID
                 UserInfo uinfo = db.UserInfoes.FirstOrDefault(x=>x.ID == id);      
                 //Check for null userInfo    
            return View(uinfo);
        }
        else
        {
            return RedirectToAction("HomeIndex");
        }
    }

【讨论】:

  • Find 始终使用主键。无需使用FirstOrDefault。此外,在 Edit 操作中解析键失败应该不会发出警报,而不是静默重定向。
  • 您的第一点已注明,但第二点应针对上述问题进行评论,因为您评论的代码属于提问者
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多