Reputation: 389
I would like to change the value of a property in the server from a button click in ASP.NET Core Razor Page.
I have this property in a class:
public class MyClassViewModel
{
public string ButtonColor { get; set; }
public MyClassViewModel()
{
ButtonColor = new string("#007BFF");
}
}
In my Razor page I am checking for a null reference exception like this:
@{ MyClassViewModel color = new MyClassViewModel(); if (string.IsNullOrEmpty(color.ButtonColor)) { color.ButtonColor = "#000000"; } }
I have a two anchors that save the user selected color to a hidden input. These tags allow the user to choose their desired color. It is like this:
<li><input type="text" id="selected-theme" value="@Model.ButtonColor" hidden readonly/></li>
<li><a style="color:rgb(7,100,199)" onclick="apply_theme('#007BFF')"><i class="fas fa-square"></i></a></li>
<li><a style="color:rgb(188,126,0)" onclick="apply_theme('#BC7E00')"><i class="fas fa-square"></i></a></li>
This is the script containing the 'apply_theme()' function:
function apply_theme(color) {
document.getElementById('selected-theme').value = color;
}
The issue here is that I am getting:
'System.NullReferenceException: 'Object reference not set to an instance of an object.''
exception on this line:
<li><input type="text" id="selected-theme" value="@Model.ButtonColor" hidden readonly/></li>
The compiler is complaining that I have not instantiated the object before getting the value, but I think I have done so in the constructor. What am I missing, or how am I getting it all wrong?
I hope to get some insight into this scenario.
Upvotes: 0
Views: 3234
Reputation: 8459
This is a simple working demo. I used the partial view.
Index View:
<li id="theme"></li>
<li><a style="color:rgb(7,100,199)" onclick="apply_theme('#007BFF')"><i class="fas fa-square">theme1</i></a></li>
<li><a style="color:rgb(188,126,0)" onclick="apply_theme('#BC7E00')"><i class="fas fa-square">theme2</i></a></li>
@section scripts{
<script>
$(function () {
$.ajax({
type: "get",
url: "/Home/SetColor",
success: function (result) {
$("#theme").html(result);
}
})
})
function apply_theme(color) {
$.ajax({
type: "get",
url: "/Home/SetColor",
data: { color: color },
success: function (result) {
$("#theme").html(result);
}
})
}
</script>
}
SetColor:
public IActionResult SetColor(string color)
{
MyClassViewModel myClassViewModel = new MyClassViewModel();
if (!string.IsNullOrEmpty(color))
{
myClassViewModel.ButtonColor = color;
}
return PartialView(myClassViewModel);
}
Partial View:
@model MyClassViewModel
<input type="text" id="selected-theme" value="@Model.ButtonColor" readonly />
Result:
Upvotes: 1