Alan2
Alan2

Reputation: 24572

Error message when I use xx.Contains in C#

I am trying the following code inside an ASP MVC Razor file:

       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);             
        }

But I get an error message:

object' does not contain a definition for 'Contains' and the best extension method overload

Upvotes: 0

Views: 120

Answers (2)

JohnnBlade
JohnnBlade

Reputation: 4327

Try this

    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);
    }

Upvotes: 2

ozczecho
ozczecho

Reputation: 8859

var topic = ViewData["TopicID"];

Returns object. You need to cast to string.

Upvotes: 7

Related Questions