2

I am trying to split the string based on ; and store it in array of string in MVC Razor view and I tried it as below:

@{
     string[] replies = !string.IsNullOrEmpty(messages.MessageReply) ? messages.MessageReply.Split(';') : new string []{};
}

But whenever I write this it will treat last } of the string[] replies as its main closing bracket instead of the one below. How can I avoid this or how would I be declaring such sort of variables in razor view?

9
  • 4
    Works fine for me. But that sort of code should be in a controller (and set the value of a view model property), not in the view Commented Mar 7, 2016 at 12:08
  • So @StephenMuecke.. This isn't possible here? Commented Mar 7, 2016 at 12:10
  • As I noted, your code works fine. What is the error your getting? Commented Mar 7, 2016 at 12:11
  • Error in the sense its treating the very next } bracket as closing bracket for @{.. Like if I use messages.MessageReply.Split(new []{';'}, StringSplitOptions.RemoveEmptyEntries) it treats } inside split as closing bracket as it will be highlighted with yellow color.. Commented Mar 7, 2016 at 12:13
  • Using .Split(new []{';'} works fine for me as well. I suspect there are other issues with your code (I can create a simple DotNetFiddle if you need the proof) Commented Mar 7, 2016 at 12:16

2 Answers 2

2

Pust conditional expression into brackets:

string[] replies = (!string.IsNullOrEmpty(messages.MessageReply) ? messages.MessageReply.Split(';') : new string []{ });

Or... just get rid of brackets:

string[] replies = !string.IsNullOrEmpty(messages.MessageReply) ? messages.MessageReply.Split(';') : new string [0];

It should help

Sign up to request clarification or add additional context in comments.

2 Comments

That would be problem if I include messages.MessageReply.Split(new []{';'}, StringSplitOptions.RemoveEmptyEntries)!!
So, you must have an other issue in your code. As I said, I've checked yout scenario and it works fine.
1

I guess you could use: string[0] instead of string[]{}:

@{
     string[] replies = !string.IsNullOrEmpty(messages.MessageReply) ? messages.MessageReply.Split(';') : new string [0];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.