accessing MVC model with in java script

社会主义新天地 提交于 2019-12-25 02:30:02

问题


Is there a way i can access model from with in java script? ... if yes then how?

I have a Model with folowing properties and i want to set few of them to variable within java script

public class BillPaymentModel
{
    public string ClassName = "BillPaymentModel";

    public BillDTO BillDTOObj { get; set; }
    public DebitablesDTO SelectedAccount { get; set; }
    public CreditablesDTO SelectedCreditCard { get; set; }
    public ExecutionSchedulingDTO ExecSchedDTO = new ExecutionSchedulingDTO();
    public string SelectedPaymentType { get; set; }
    public PaymentCompanyDTO PayCompanyDTO { get; set; }
    public List<SelectListItem> fromAccountNumberList { get; set; }
    public IList<BeneficiaryDTO> List_Beneficiaries { get; set; }
    public SelectList AccountsList { get; set; }
    public SelectList CreditCardsList { get; set; }
    public SelectList AmountList { get; set; }
    public Dictionary<string, string> Test { get; set; }
    public string SinglePaymentTypeAttribute { get; set; }
    public string[] AllPossibleAmounts { get; set; }
    public string PaymentMode { get; set; }
    public string TransactionReference { get; set; }
    public double AmountPaid { get; set; }
}

is it possible if i do some thing like:

    var TempVariable=Model.SomeAttribute;

回答1:


You will have to write actions in your controller to set and get these properties.

These actions can be called in javascript, using the jquery method $.ajax

To set a attribute in the object call the set action.

$.ajax({
    url:'path_to_set_action',
    type:'POST',
    data:{ variable_name: value },
    success:function(){
        //do something once attribute is set
    }
});

The above function works in the same way as a form post, and the data can be accessed in the action using Request["variable_name"]

To get the value of an attribute in the object call the get action.

$.ajax({
    url:'path_to_get_action',
    success:function(data){
        alert(data.value);
    }
});

In your get action...

return Json(new {value=YourVariable }, JsonRequestBehavior.AllowGet);

Also since a MVC application is stateless, you will have to store your objects state either in a session variable or in the database.




回答2:


is it possible if i do some thing like:

var TempVariable=Model.SomeAttribute;

Yes.

If you have some <script> tags in your view, you can do exactly that.

<script>
    var myVar = @Model.Name;
    alert("Hello, " + myVar);
</script>


来源:https://stackoverflow.com/questions/24623712/accessing-mvc-model-with-in-java-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!