Reputation: 2249
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;
Upvotes: 0
Views: 635
Reputation: 86
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.
Upvotes: 1
Reputation: 16348
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>
Upvotes: 1