Home Execute a C# method from html Razor page
Reply: 0

Execute a C# method from html Razor page

PRHMN Published in 2018-01-10 12:18:04Z

I'm developing a simple .NET Core Razer project based on this tutorial: https://docs.microsoft.com/en-us/aspnet/core/data/

I've created 2 models related in one-to-many relation, just like header-detail. I got header which, after clicking, views all it's details. I would like a button for each of those detail rows that takes it 1 up or 1 down in order. I've created a method in Index.cshtml.cs that does it, but now I need to run this method from Index.cshtml. I tried something like this:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
    function RuleStepMoveUp() {

        var RSO = '@Model.RuleStepMoveUp()';


and there's a button to execute it:

      <input type="button" onclick="RuleStepMoveUp()" value="Get Message" />

for each of the details, but it doesn't work. RuleStepMoveUp() method executes everytime the page is loaded, and the page fails with error:

NullReferenceException: Object reference not set to an instance of an object. WZI_Konfigurator.Pages.Rules.Index_Page+d__15.MoveNext() in Index.cshtml + 28. @foreach (var item in Model.Rule.Rules)

@foreach (var item in Model.Rule.Rules)
            string selectedRow = "";
            if (item.RuleID == Model.ID)
                selectedRow = "success";

            <tr class="@selectedRow">
                    @Html.DisplayFor(modelItem => item.RuleName)
                    @Html.DisplayFor(modelItem => item.Stage)
                    @Html.DisplayFor(modelItem => item.ResultColumn)
                    <a asp-page="./Index" asp-route-id="@item.RuleID">Select</a> |
                    <a asp-page="./Edit" asp-route-id="@item.RuleID">Edit</a> |
                    <a asp-page="./Details" asp-route-id="@item.RuleID">Details</a> |
                    <a asp-page="./Delete" asp-route-id="@item.RuleID">Delete</a>


Even though it loads fine when the JS script is not there.

Right now C# method does the update on one, hardcoded, detail entity to make sure it's working. In the future I will just pass detailID in RuleStepMoveUp method, so that's why there are no parameters.

That's how the page looks after I deleted the JS function

So, how should I approach this to execute the C# method only when the "Get Message" button is clicked? Also, is there a nice and smooth way to update the table for Rule Steps without refreshing the page?

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.405971 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO