MVC3 Pass Model view to controller using javascrip

2019-09-08 17:34发布

I am trying to pass model from view to controller using javascript. But it returns null values.

Here is my view Newcamp.chstml

 <input type="submit" value="Preview" id="ClickMe" class="cssLoginButton blue"/>

<script type="text/javascript">
 function OpenWindow(query, w, h, scroll) {
     var l = (screen.width - w) / 2;
     var t = (screen.height - h) / 2;

     winprops = 'resizable=0, height=' + h + ',width=' + w + ',top=' + t + ',left=' + l + 'w';
     if (scroll) winprops += ',scrollbars=1';
     var f = window.open(query, "_blank", winprops);
 }


 $(function () {
     $('#ClickMe').click(function () {
             OpenWindow('@Url.Action("NewCampEmail", "Camp",new{model = @Model})', 700, 700, true);
     });
 });
</script>

My controller action NewCampEmail

    [HttpGet]
    [OutputCache(Location = OutputCacheLocation.None)]
    [Authorize]
    public ActionResult NewCampEmail(Models.NewCamp model)
    {            
        return ReturnModelWithEmailType(model,EmailType.NewCampEmail);
    }

In model I get null values. Why I am getting null values? Is there any change in my code? My model is same in NewCamp.chstml i.e. Models.Newcamp

1条回答
啃猪蹄的小仙女
2楼-- · 2019-09-08 18:18

you can't pass the @Model via javascript in this way. the Model ONLY exists on the serverside and is used in page creation ahead of the http response sending it back. You can of course get 'values' from the model and sent them as contants to the controller but there's no way to reference the actual Model per-se in this way.

Your best bet would be to look at knockoutjs (a great excercise irrespective) or similar if you want to refer to a single Model, rather than properties on the page etc.

In a nutshell, once the page has been rendered, the @Model is gone and can only be referenced via page properties or javascript objects populated by the @Model...

查看更多
登录 后发表回答