简体   繁体   中英

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM