简体   繁体   English

具有模型属性的AJAX帖子

[英]AJAX post with model property

I want to do Something like 我想做类似的事情

$.ajax({
    url: '/Home/AjaxTest', 
    data: {
        id: @Model.Prop
    },
    type: 'post',
    cache: false, 
    success: function (response) {
        console.log(response);
    }
    ...

However, It didn't work. 但是,它没有用。 I know that if I have a hidden field for it, like 我知道如果我有一个隐藏字段,例如

@Html.HiddenFor(model => model.Id)

then I can get the property value by 然后我可以通过

data: { id: $('input[name="Id"]').val() },

Still I wonder. 我还是很奇怪。 Are there any way else to access the Model property more directly? 还有其他方法可以更直接地访问Model属性吗?

data: { id: "@Model.Prop" } // may or may not need quotes depending on data type.

If you do this, it will be the value of the Model.Prop field at the time of rendering the page so any modifications to inputs using that property will not be reflected. 如果这样做,它将是呈现页面时Model.Prop字段的值,因此使用该属性对输入所做的任何修改都不会反映出来。

If you want the actual data from an input control that has been rendered using EditorFor, etc: 如果要从使用EditorFor等渲染的输入控件中获取实际数据,请执行以下操作:

data: { @(Model.Prop.GetType().Name): $('input[name="@(ViewData.TemplateInfo.HtmlFieldPrefix + "." + Model.Prop.GetType().Name)"]').val() }

This will render the javascript using the property name as the json index and the same name but including the model (and any containing models) prefix as the name of the element to find the value of. 这将使用属性名称作为json索引和相同的名称(但包括模型(以及任何包含模型)的前缀)作为要查找其值的元素名称的名称来呈现javascript。

Yes you can do if you follow the Model pattern of java script. 是的,如果您遵循Java脚本的Model模式,则可以执行此操作。 This is your java script file. 这是您的Java脚本文件。

var JSModel = (function(){

       var model = {};


       var init = function(){
           //Perfome your operations
         };

       return {
        init:init,
        model :model  //return beacuse we want to acccess it in cshtml
      };

    })();


    $(document).ready(function() {
        JSModel .init();
    });

Now in cshtml, you will do this: //Invlude your JS file here and then 现在在cshtml中,您将执行以下操作://在此处包含JS文件,然后

<script>
JSModel.model = @Html.Raw(Json.Encode(Model)); // You will get the model in your js file. it will in JSON form

</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM