我在ASP MVC Razor文件中尝试以下代码:
var topic = ViewData["TopicID"];
var mustBeReplaced = string.Empty;
var topicValue = Model.Topic;
var replaceResult = string.Empty;
if (topic.Contains(topicValue)) {
mustBeReplaced = "value=\"" + topicValue + "\"";
replaceResult = mustBeReplaced + " selected=\"selected\"";
topic = topic.Replace(mustBeReplaced, replaceResult);
}
但是我收到一条错误消息:
object'不包含'Contains'的定义和最佳扩展方法重载
答案 0 :(得分:7)
var topic = ViewData["TopicID"];
返回对象。你需要转换为字符串。
答案 1 :(得分:2)
试试这个
var topic = (string)ViewData["TopicID"];
var mustBeReplaced = string.Empty;
var topicValue = "11111";
var replaceResult = string.Empty;
if (topic.Contains(topicValue))
{
mustBeReplaced = "value=\"" + topicValue + "\"";
replaceResult = mustBeReplaced + " selected=\"selected\"";
topic = topic.Replace(mustBeReplaced, replaceResult);
}