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).

3
  • 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. Commented Aug 17, 2021 at 11:59
  • Sorry, my wording is bad. I've edited my OP. Commented Aug 17, 2021 at 12:05
  • I would recommend the use of Partial or ViewComponents. 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 and update it as needed. Commented Aug 17, 2021 at 12:32

3 Answers 3

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)
}
Sign up to request clarification or add additional context in comments.

4 Comments

@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.
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: 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...
Ah okay, I think that makes sense. I'll change that ;) Thank you, you helped me alot
0

try this

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

2 Comments

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?
you view should be the same anyway - so no need to update - unless someone else changes it
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.

3 Comments

Not sure if I understand correctly, but what would a reload change? (Since the problem is, that the model doesn't recognize the changes made in the view)
Maybe I understand your question wrongly. I thought your view is not reflecting new changes after you made the ajax call.
Not your fault, I was wording my question badly. I've edited my OP.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.