CircleHsiao CircleHsiao - 4 years ago 107
Javascript Question

AJAX post with model property

I want to do Something like

url: '/Home/AjaxTest',
data: {
id: @Model.Prop
type: 'post',
cache: false,
success: function (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?

Answer Source
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.

If you want the actual data from an input control that has been rendered using EditorFor, etc:

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download