Cannot convert type 'char' to 'string

Cannot convert type 'char' to 'string



I am getting this error in one project and the code works perfectly fine on another project. I have tried multiple to duplicate the code as it is. Is there a way to find where the error originated from??


@if (ViewBag.RolesForThisUser != null)
{
<div style="background-color:lawngreen;">
<table class="table">
<tr>
<th>
@Html.DisplayName("Roles For This User")
</th>
</tr>
<tr>
<td>
@foreach (string s in ViewBag.RolesForThisUser) //this line

<li>@s</li>

</td>
</tr>
</table>




1 Answer
1



I suspected ViewBag.RolesForThisUser itself already contains a string, neither an array nor collection of strings (e.g. string or List<string>), hence using foreach loop is pointless (and string itself contains char array which explains why type conversion failed). You can simply display it without foreach:


ViewBag.RolesForThisUser


string


string


List<string>


foreach


string


char


foreach


@if (!string.IsNullOrEmpty(ViewBag.RolesForThisUser))

<div style="background-color:lawngreen;">
<table class="table">
<tr>
<th>
@Html.DisplayName("Roles For This User")
</th>
</tr>
<tr>
<td>
@ViewBag.RolesForThisUser
</td>
</tr>
</table>
</div>



Or assign a string collection to ViewBag.RolesForThisUser from GET method so that you can use foreach loop, like example below:


ViewBag.RolesForThisUser


GET


foreach



Controller


public ActionResult ActionName()

var list = new List<string>();

list.Add("Administrator");
// add other values here

ViewBag.RolesForThisUser = list;

return View();



View


@if (ViewBag.RolesForThisUser != null)

<div style="background-color:lawngreen;">
<table class="table">
<tr>
<th>
@Html.DisplayName("Roles For This User")
</th>
</tr>
<tr>
<td>
@foreach (string s in ViewBag.RolesForThisUser)

<p>@s</p>

</td>
</tr>
</table>
</div>



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế