0

This is the Controller that returns the above-mentioned view:

    public PartialViewResult Day()
    {
        Day model = new Day();
        return PartialView("_Day", model);
    }

    [HttpPost]
    public PartialViewResult Day(Day model)
    {
        return PartialView("_Day", model);
    }

I wrote both the Get and the Post method after I read this question. Note that I haven't set the model in the Controller.

Then I have my View:

@model Timing.Models.Day

@{
    Timing.Models.Day d = new Timing.Models.Day();
    d.UserId = "some value";
}

This piece of code is working fine: when I go to retrieve, or display, d.UserId I get the right value.
Furthermore I have a script in the same view.

<script>
    function getUserId() {
        //some code that gets a string
        return userId;
    }
</script>

And also this script is working right.
I looked for a solution and this is the best I've been able to find:

@{
    Timing.Models.Day d = new Timing.Models.Day();
    d.UserId = Page.ClientScript.RegisterStartupScript(this.GetType(), "Getuser", "getUserId()", true);
}

But it's not working because of something that is null (I wasn't able to understand what was null though).
Is there a way to solve this problem?

For those who ask, I'm using a script because the value I want to set is the one of an html element (this is my related question).
Thanks!

Community
  • 1
  • 1
xnr_z
  • 1,161
  • 2
  • 18
  • 34

2 Answers2

0

Declare your variable you want in javascript

@{
  var useridForjs = model.property // access model and set useridForjs 
}

to use in javascript

<script>
function getUserId() {
    //some code that gets a string

  var myserversidevarvalue = '@useridForjs'; // here myserversidevarvalue will store value..
    return userId;
}
</script>
Vishal Sharma
  • 2,773
  • 2
  • 24
  • 36
  • Is it possible, ie, to do the opposite process? I mean, if in the script function I write `'@Model.property' = "somevalue";` (maybe in the document ready function) does the View recognize that property with that value? – xnr_z Nov 22 '13 at 12:03
  • but if you want to store only id then do in some hidden variable and then grab data at post time from that hidden variable using request form parameters – Vishal Sharma Nov 22 '13 at 12:53
0

Make it easy on yourself and inject your id into a hidden form field, easily obtainable by javascript. Add this to your view:

 Html.HiddenFor(model.userId)

Then access it like this:

 function getUserId() {
    return $('#userId').val();
}
Mister Epic
  • 16,295
  • 13
  • 76
  • 147