js:RazorビューでサーバコードがJavascript変数に割り当てられます.

3679 ワード

namespace Razor.Controllers
{
    public class JSController : Controller
    {
        public ActionResult Index()
        {
            List<string> FriendsId = new List<string> { "S1", "S2", "S3", "S4" };
            ViewBag.FriendsId = FriendsId;
            return View();
        }
    }
}
 
 
@{
    ViewBag.Title = "Index";
}
<h2>Index</h2>
<script type="text/javascript">
var array = new Array();
@{   
 string message=""; 
}
@for (int i = 0; i < 3; i++) {
    message += "array[" + i + "]=\"" + ViewBag.FriendsId[i] + "\";";
}
@MvcHtmlString.Create(message);
alert(array[0]);
</script>
 
 
public class PersonModel

    {

        public string Name { get; set; }

        public int Age { get; set; }

    }
 
static List<PersonModel> DummyData()

        {

            var data = new List<PersonModel>()

                           {

                               new PersonModel()

                                   {

                                       Name = "Tom",

                                       Age = 20

                                   },

                               new PersonModel()

                                   {

                                       Name = "Cat",

                                       Age = 5

                                   }

                           };

            return data;

        }
 
public ActionResult Index()

        {

            var data=DummyData();

            return View(data);

        }
 
<script >

        $(function() {

            var model = <%= new JavaScriptSerializer().Serialize(Model) %>;

            debugger;

        }) 

    </script>
 
<script >

        $(function() {

            var model = <%= new JavaScriptSerializer().Serialize(Model) %>;

            alert(model[0].Name);

            debugger;

        }) 

    </script>