简体   繁体   中英

Pass last insert id to toastr - Asp.Net MVC 4

I am new to MVC and trying to pass the last created Id (once the save button has been clicked in the form).

Can anyone please tell me if it is possible to pass this value to the toastr display, and how this can be done, so once the save button is pressed it returns that Id number?

Additionally to my comment, here's a more complex answer.

Roughly it contains the following items:

  • Views: CreateItem, NewItemHandler
  • Controllers: ItemHandler
  • Javascript: site.js and jQuery

The CreateItem view is the dialog where the user enters their item values. In my case a simple form with two input fields and the mandatory submit button.

@{
    ViewBag.Title = "CreateItem";
}

<h2>CreateItem</h2>

<form id="newItemForm">
    Item name: <input id="itemname" type="text" name="fname"><br>
    Item weight: <input id="itemweight" type="text" name="lname"><br>
    <input type="submit" value="Submit">
</form>

The JavaScript should stop the redirection when clicking on submit , this is done by returning false within $("newItemForm").submit(...) . Furthermore we no need to tell the server that it needs to create our item, so we have to create our own submit request, which I did with jQuery.post() :

$('#newItemForm').submit(function () {
    sendPostAndShowResult();
    return false;
});

function sendPostAndShowResult() {
    var name = $("#itemname").text();
    var weight = $("#itemweight").text();
    $.post("/Item/NewItemHandler",
        { "name": name, "weight": weight }
    ).done(function (data) {
        alert("The ID of your new item is: " + $.trim(data)); //replace with toast
    })
    .fail(function () {
        alert("Error while processing the request!");
    });
}

Just a hint: I didn't use toast here, since I never used it, but I guess it shouldn't be too difficult to adapt.

The final piece of the puzzle is the NewItemHandler , which creates the item, figures out the ID and returns the value:

The View is quite easy. Since we don't need a Layout, it has been set to "".

@{
    Layout = "";
}
@Html.Raw(Session["ItemID"])

As you see, we just need to get the "ItemID" into our Session object, this is done by the Controller.

[HttpPost]
public ActionResult NewItemHandler(string name, string weight)
{
    int id = GenerateNewItem(name, weight);
    Session["ItemID"] = id;
    return View();
}

EDIT: I tried to adapt this approach to your solution:

You need to remove the return RedirectToAction() with return View(); in your Controller. This then returns ( Save.cshtml ) a response, with the ID in an ohterwise empty file ( Layout = "" ). Your Save.cshtml is empty I guess, so replace it with

@{
    Layout = "";
}
@Html.Raw(Session["ItemID"])

In your controller the Save Method should look remotely like this.

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Save(BidstonHwrc bidstonhwrc)
    {
        _context.BidstonHwrc.Add(bidstonhwrc);

        try
        {
            _context.SaveChanges(); //either all changes are made or none at all
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }

        int id = bidstonhwrc.Id;
        Session["ItemID"] = id;
        return View();
    }

In your MCN Form you need to give your <form> tag an ID, via Razor:

@using (Html.BeginForm("Save", "BidstonHwrc",FormMethod.Post, new { id = "SaveBidstonHwrc" }))

The code should look like this, simply adapt the IDs:

$('#SaveBidstonHwrc').submit(function () {
    sendPostAndShowResult();
    return false;
});

function sendPostAndShowResult() {
    //foreach Model/ViewModel Property one line e.g.
    var Id = $("Id").text();
    var McnNumber = $("McnNumber").text();
    $.post("/BidstonHwrc/Save",
        { "Id": Id, "McnNumber": McnNumber }
    ).done(function (data) {
        alert("The ID of your new item is: " + $.trim(data)); //replace with toast       
        $(location).attr('href', '/Home/Index') //Redirect to Home
    })
    .fail(function () {
        alert("Error while processing the request!");
    });
}

I uploaded a project that should represent your solution a bit.
You can download it here (28MB): Project download

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM