Berkan Toptaş
Berkan Toptaş

Reputation: 21

ASP.NET MVC transfer data from controller to view with viewmodel

In my controller I have

public ActionResult Index()
{
    //...
    //...
    var viewModel = new IndexViewModel()
    {
        MTohum = mTohum,
        STohum = sTohum,
        BTohum = bTohum,
        TKota = tKota,
        KKota = kKota,
        BKota = bKota,
    };
    //return Content("tkota : " + tKota.ToString() + " kkota : " + kKota.ToString() + " bkota : " + bKota.ToString());
    return View(viewModel);
}

When I remove comment and return Content() I can see that values are not null.

On the view side:

//..html codes..//

<script>
    $(document).ready(function () {
        alert(@Model.TKota);
        alert(@Model.KKota);
        alert(@Model.BKota);
        alert(@Model.TKota + " " + @Model.KKota + " " + @Model.BKota);
    });
</script>

My problem is: 1st, 2nd and 3rd alerts showing right info but when I trying to take all info in one alert like 4th, I can get @Model.TKota, @Model.KKota but I can't get @Model.BKota value.

Consequently I can't use @Model.BKota in the following lines.

Upvotes: 1

Views: 157

Answers (2)

Stephen Byrne
Stephen Byrne

Reputation: 7485

The clue is that you are not able to work with the variables after that statement, this usually means the parser has choked on something due to a syntax error.

alert("@Model.TKota + " " + @Model.KKota + " " + @Model.BKota); looks like a syntax error would occur here due to the opening " not being closed.

Try this:

alert('@Model.TKota @Model.KKota @Model.BKota');

Upvotes: 0

Eric Herlitz
Eric Herlitz

Reputation: 26267

Your last alert is badly formatted, it should look like this

alert('@Model.TKota @Model.KKota @Model.BKota');

See the following fiddle

https://dotnetfiddle.net/yc8F4Q

Upvotes: 3

Related Questions