开发者

Controller returns the contents of the array, but in my view i only get the type? MVC

I Have a controller that returns a viewModel.

That viewModel has a property called Users, which is an array of all usernames that currently have an account in the system. This is used for a jquery tagging plugin.

The Users property correctly sends an array to the view

But when i use @Model.Users in the view i just get the type ie; System.String[]

I guessing this is something ridiculously simple to solve.

Controller

public virtual ActionResult Create(int id)
    {

        var viewModel = new AttendeeViewMode开发者_如何学Cl();

        var data = viewModel.GetMembershipUserList() ;
        viewModel.MeetingID = id;

        viewModel.Users = data.ToArray();

        return View(viewModel);
    } 

ViewModel

public class AttendeeViewModel
{

    public int AttendeeId { get; set; }
    public string Name { get; set; }
    public int MeetingID { get; set; }
    public string[] Users { get; set; }

    public List<string> GetMembershipUserList()
    {
        List<string> userNames = new List<string>();
        foreach (MembershipUser user in Membership.GetAllUsers())
        {
            userNames.Add(user.UserName);
        }

        return userNames;

    }
}

View Usage

<script type="text/javascript">

    var tags = @Model.Users

    $(document).ready(function () { $("#mytags").tagit({ availableTags: tags }); });


</script>


@Model.Users is the equivalent to dumping Model.Users.ToString() into the view. For your particular use you need to render it as a JavaScript array. A C# string array has no idea how to do this. Something like :

 var tags = [ @( string.Join("," Model.Users.Select(s => "'" + s + "'").ToArray()) ) ];

Although it's probably better to do this from the ViewModel and just have Model.UsersAsJavaScriptArray or something like that. If I was doing this often I'd probably create an extension method for HtmlHelper and do @Html.AsJavaScriptArray(Model.Users)


Like Matt said when you try to output something using <%= %> or @ it's just going to .ToString() it.

Instead you could try...

ViewModel.UsersJson = new JavascriptSerializer().Serialize(data.ToArray());

Or even only serialize the things you need...

ViewModel.UsersJson = new JavascriptSerializer().Serialize(data.ToArray().Select(u => new { Username = u.Username, FirstName = u.FirstName });

...

var tags = @Model.UsersJson
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜