2

I want to pass the value i got it from model to the java-script function

 <script type="text/javascript">
 
 var checkin = @Model.Parameters.Checkin.ToString("dd-MM-yyyy");
        var checkout = @Model.Parameters.Checkout.ToString("dd-MM-yyyy");
        
 </script>

this function that i want to pass model chick-in and chick-out value to it:

$('document').ready(function () {       

   $("#Arrival").val(checkin);
  $("#Departure").val(checkout); 
 });

i tried many solution but it didn't work yet . any advice, thanks

7
  • 1
    if the @Model has value try checkin = '@Model.Parameters.Checkin.ToString("dd-MM-yyyy")'; Commented May 16, 2017 at 10:48
  • inside the script var obj = '@(Model.Parameters.Checkin.ToString("dd-MM-yyyy"))' Commented May 16, 2017 at 10:51
  • @AsifRaza i replaced still not working , i get the value from model inside script in the view.cshtml but inside js.file i can not get the value from the model ? Commented May 16, 2017 at 11:07
  • '@(Model.Parameters.Checkin)' try this one , and make sure are you getting value inside Parameter.Checkin ? Commented May 16, 2017 at 11:08
  • @AsifRaza Now , when i tried to put your line inside $('document').ready(function () { }); function i can not get the value it gives me this line @(Model.Parameters.Checkin) but if set it the view.chtml i get the value correctly ?? Commented May 16, 2017 at 11:18

2 Answers 2

8

if the @Model.Parameters.Checkin and @Model.Parameters.Checkout not null then Try:

 <script type="text/javascript">

$( document ).ready(function(){       
 var checkin = '@Model.Parameters.Checkin.ToString("dd-MM-yyyy")';
 var checkout = '@Model.Parameters.Checkout.ToString("dd-MM-yyyy")';

   $("#Arrival").val(checkin);
  $("#Departure").val(checkout); 
 });

Just you miss '. and also change $('document').ready(function () { }) to $(document).ready(function () { }).

you must write all script into a .cshtml file. @Model.Parameters.Checkin.ToString("dd-MM-yyyy") never work into a .js file.

Because, In .cshtml, when the the page is render then it white to HTTP response stream as a string.

Sign up to request clarification or add additional context in comments.

1 Comment

Best practices say you should not mix C# and Javascript. I think you should pass your model in HTML attributes.
0

In MVC, you can use following code:

<script type="text/javascript">
    var number = parseInt(@ViewBag.Number); //Accessing the number from the ViewBag
    alert("Number is: " + number);
    var model = @Html.Raw(@ViewBag.FooObj); //Accessing the Json Object from ViewBag
    alert("Text is: " + model.Text);
</script> 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.