Home » c# » c# – Razor view model binding use javascript function-Exceptionshub

c# – Razor view model binding use javascript function-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have following model binding in reazor view .cshtml

@Html.TextBoxFor(m => m.cDate,
    new{
        @id = "textd",
        @type = "text"
    }
)

I want to call a javascript function before binding like below

@Html.TextBoxFor(m => updatedateFormat(m.cDate),
    new{
        @id = "textd",
        @type = "text"
    }
)

updatedateFormat is a javascript function.

I do have many options to do with c# only, But I am curious to know can we use javascript function with model binding.

I tried like below

@{
  string ccDate= @Convert.ToString("updatedateFormat(@Model.cDate)");
}
@Html.TextBoxFor(m => ccDate,
new

But not working

Please advise.
Thanks

How to&Answers:

Since it is not possible to trigger a Javascript function, when an input element or any other html element is rendered, you can use the document.ready event to achieve what your want:

@Html.TextBoxFor(m =>m.cDate,
    new{
        @id = "textd",
        @type = "text",
    }
)

And when the document is ready:

$(document).ready(function () {
    var ccDate= document.getElementById('textd');
    updatedateFormat(ccDate);
})

Or you could add a custom attribute such as data-onload to simulate a on load event:

@Html.TextBoxFor(m => m.cDate,
    new{
        @id = "textd",
        @type = "text",
        data_onload="updatedateFormat('@Model.cDate')"
    }
)

And when the document is ready:

$(document).ready(function () {
    $('[data-onload]').each(function(){
    eval($(this).data('onload'));
  });
})

If you only want to format the value of your property, you can do that using ToString() function inside the HTML helper:

@Html.TextBoxFor(m =>m.cDate,
    new{
        @id = "textd",
        @type = "text",
        @Value = Model.cDate.ToString("yyyy/MM/dd")
    }
)