1

I'm trying to make a simple ASP.NET Core MVC application which updates / inserts / displays data from our database. I have models written like this (similar to the db fields):

public class INVOICE : ModelBase
{
    [Key]
    public decimal ID { get; set; }
    public string CONTRACTID { get; set; }
    public string ORDERID { get; set; }
    public decimal? INVOICEAMOUNT { get; set; }
    public string BARCODE { get; set; }
    ...
}

(with some more functionality like db update / insert)

I have one controller:

public class HomeController : Controller
{
    // GET: HomeController
    INVOICE invoice = CRUD.GetFirstOrDefault(new INVOICE(), @"WHERE ID IN (75693)");
    public ActionResult Index()
    {
        return View(invoice);
    }
 
    [HttpPost]
    public bool Update()
    {
        return invoice.Update();
    }
}

And the Index.cshtml:

<body>
    <div class="form-group">
        <label>Barcode</label>
        <input type="text" class="form-control" id="BARCODE" placeholder="0" value="@Model.BARCODE" readonly>
    </div>
    <div class="form-group">
        <label>Id</label>
        <input type="text" class="form-control" id="ID" placeholder="0" value="@Model.ID" readonly>
    </div>
    <div class="form-group">
        <label>INVOICEAMOUNT</label>
        <input type="text" class="form-control"  name="INVOICEAMOUNT"  id="INVOICEAMOUNT" value="@Model.INVOICEAMOUNT" aria-describedby="emailHelp" placeholder="0">
    </div>

    <form id="formUpdate">
        <div>
            <asp:button id="Button" class="btn btn-primary">Update</asp:button>
        </div>
    </form>

    @section Scripts{
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>      

        <script>
                $(function () {
                    $("#Button").click(function () {
                        $.ajax({
                            type: "POST",
                            url: "/Home/Update",

                            success: function (response) {
                                console.log(response);
                            },
                            failure: function (response) {
                                alert("Fail");
                            },
                            error: function (response) {
                                alert("error");
                            }
                        });
                    });
                });
        </script>        
    }
</body>

But now, when I'm clicking the button after I changed the Inputfield value of the INVOICEAMOUNT, the update is called and successful, but the values are the same as they where when I initialized the model. How do I tell my model that the values got changed?

Edit: My wording is bad. The Update is working, but the update isn't using the values that are displayed in the view. It's still using the values I initialized, even though I changed the input field values (clicked in it, wrote a new number).

Jackdaw
  • 7,626
  • 5
  • 15
  • 33
user3793935
  • 411
  • 5
  • 22
  • You have to make an ajax call to reload your new data after it gets updated. after console.log(response); code, in this block you can write your data retrieve. – Reza Akraminejad Aug 17 '21 at 11:59
  • Sorry, my wording is bad. I've edited my OP. – user3793935 Aug 17 '21 at 12:05
  • I would recommend the use of [Partial](https://www.learnrazorpages.com/razor-pages/ajax/partial-update) or [ViewComponents](https://www.learnrazorpages.com/razor-pages/view-components). You can invoke them from your page and after your post do it again; that way there's no need to reload the entire page (I suppose that's the main purpose). You can also make, for example a [Javascript Table](https://stackoverflow.com/questions/14643617/create-table-using-javascript/14644462) and update it as needed. – Henrique Pombo Aug 17 '21 at 12:32

3 Answers3

1

It is possible to use Html.BeginForm() to achieve what you trying to implement.

After pressing on the Update button an updated INVOICE model will POSTed to Update(INVOICE invoice) action.

The controller side:

public class HomeController : Controller
{    
    public ActionResult Index(INVOICE model = null)
    {
        if (model == null || model.ID == 0)
        {
            model = CRUD.GetFirstOrDefault(new INVOICE(), @"WHERE ID IN (75693)");
        }
        return View(model);
    }

    [HttpPost]
    public ActionResult Update(INVOICE invoice)
    {
        if (ModelState.IsValid)
        {            
            // TODO: additional logic to save the updated `invoice` record

        }           
        return View("Index", invoice);           
    }
}

The Index view:

@model Models.INVOICE
@{
    ViewBag.Title = "Index";
}

@using (Html.BeginForm("Update", "Home"))
{
    @* @Html.ValidationSummary(); *@

    <div class="form-group">
        @Html.LabelFor(m => m.BARCODE)
        @Html.TextBoxFor(m => m.BARCODE, new { @class = "form-control", placeholder = "0" })
        @Html.ValidationMessageFor(m => m.BARCODE)
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.ID)
        @Html.TextBoxFor(m => m.ID, new { @class = "form-control", placeholder = "0" })
        @Html.ValidationMessageFor(m => m.ID)
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.INVOICEAMOUNT)
        @Html.TextBoxFor(m => m.INVOICEAMOUNT, new { @class = "form-control", placeholder = "0", aria_describedby="emailHelp" })
        @Html.ValidationMessageFor(m => m.INVOICEAMOUNT)
    </div>

    <button type="submit" class="btn btn-primary">Update</button>

    @Html.HiddenFor(m => m.CONTRACTID)
    @Html.HiddenFor(m => m.ORDERID)
}
Jackdaw
  • 7,626
  • 5
  • 15
  • 33
  • @user3793935: I've changed your [asp.net-core] tag to [asp.net-mvc] because your method signature indicates that you're using ASP.NET (.NET Framework) rather than ASP.NET Core. If this isn't correct, please update your tags so that they all match. Regards. – Jackdaw Aug 17 '21 at 13:32
  • wich method do you mean exactly ? I followed a tutorial that was labeled as asp.net core, to set up the first controler / first view stuff. A little bit confusing if you're new and can't tell the difference yet ;( – user3793935 Aug 18 '21 at 04:38
  • 1
    @user3793935: Usually in the ASP.NET Core MVC the `IActionResult` return type is used, to be support cases when multiple `ActionResult` return types possible in an action. It confused me. Rolling back... – Jackdaw Aug 18 '21 at 05:55
  • Ah okay, I think that makes sense. I'll change that ;) Thank you, you helped me alot – user3793935 Aug 18 '21 at 06:30
0

Updated

Your form fields (inputs) should be within your form element.

<form id="formUpdate">
    <div class="form-group">
        <label>Barcode</label>
        <input type="text" class="form-control" id="BARCODE" placeholder="0" value="@Model.BARCODE" readonly>
    </div>
    <div class="form-group">
        <label>Id</label>
        <input type="text" class="form-control" id="ID" placeholder="0" value="@Model.ID" readonly>
    </div>
    <div class="form-group">
        <label>INVOICEAMOUNT</label>
        <input type="text" class="form-control" name="INVOICEAMOUNT" id="INVOICEAMOUNT" value="@Model.INVOICEAMOUNT" aria-describedby="emailHelp" placeholder="0">
    </div>

    <div>
        <asp:button id="Button" class="btn btn-primary" type="submit">Update</asp:button>
    </div>
</form>

And your controller should accept your model as parameter

[HttpPost]
public bool Update(INVOICE model)
{
    invoice.BARCODE = model.BARCODE;
    invoice.ORDERID = model.ORDERID 
    .... .    
    return invoice.Update();
}

And last remove button click event as we changed the button type to submit it will automatically do the form post. No need to have a button click and ajax call.

Abhilash Augustine
  • 4,128
  • 1
  • 24
  • 24
0

try this

[HttpPost]
public bool Update(INVOICE model)
{
    invoice.BARCODE = model.BARCODE;
    invoice.ORDERID = model.ORDERID 
    .... .    
    return invoice.Update();
}
Dai Bok
  • 3,451
  • 2
  • 53
  • 70
  • That was my first idea too. but I don't know how to pass the model back to the controller. Do you have a suggestion for that too? – user3793935 Aug 17 '21 at 12:15
  • you view should be the same anyway - so no need to update - unless someone else changes it – Dai Bok Aug 17 '21 at 13:58