MVC - Can I set a model attribute in the view and get the value form a script?

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!

Answers


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>

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();
}

Need Your Help

WebDriver unable to locate element (link/Java)

java html selenium webdriver

I'm using Selenium to navigate a webpage which has a link called "Mail", using WebDriver (just recently switched from RC to WebDriver). I want to click on the link but the testcase always fails wi...

Blobstore fo App Engine is free for api call?

google-app-engine blobstore datastore

Datastore is very exspensive because of read/write ops price (not storing price).