Tsukasa
Tsukasa

Reputation: 6552

using javascript to assign value to model

i'm using a calendar and I need to pass the value from it into my model to be submitted back to the controller but i'm stuck.

View

<div class="cell">
    @Html.LabelFor(model => model.ExpectedDatetimeStamp, new { @class = "control-label col-md-2" }):
    <div data-role="calendar" data-week-start="1" data-multi-select="false" id="c1" class="calendar"></div>
        <div hidden>@Html.EditorFor(model => model.ExpectedDatetimeStamp)</div>
    <div>
        @Html.ValidationMessageFor(model => model.ExpectedDatetimeStamp)
    </div>
</div>

<div>
    <input type="submit" value="Create" class="button primary" />
</div>

JS

function get_dates(){
    var result = $("#c1").calendar('getDates');
    alert(result);
}

how can I assign the value from result to model.ExpectedDatetimeStamp when the user presses the submit button?

Upvotes: 3

Views: 5285

Answers (2)

Travis J
Travis J

Reputation: 82267

The HTML helper you use will assign the input the id of ExpectedDatetimeStamp. Simply target it in your get dates function, and attach that function in the callback of a submit event on the closest form to the .cell element. If you are using MomentJS, then the call to calendar should be getDate. Further, in order to properly assign a value to the input as opposed to the moment object, you may want to use .format()

function get_dates(){
 var result = $("#c1").calendar('getDate').format();
 $('#ExpectedDatetimeStamp').val(result)
}

$('.cell').closest('form').submit(function(){
 //..any other values that need to be populated
 get_dates();
});

Upvotes: 0

Jane S
Jane S

Reputation: 1487

As per comments, each item in your model is given a name that matches its name in the model. So for example, your item ExpectedDatetimeStamp would have an element with that name.

So to set the value, simply use:

$('#ExpectedDatetimeStamp').val(result);

And done! :)

Upvotes: 3

Related Questions