Updating part of an ASP.NET Core MVC View which uses Forms

This article shows how to update part of an ASP.NET Core MVC view which uses forms. Sometimes, within a form, some values depend on other ones, and cannot be updated on the client side. Changes in the form input values sends a partial view update which updates the rest of the dependent values, but not the whole MVC View. This can be implemented using ajax requests. The values can then be used to do a create, or an update request.

Code: https://github.com/damienbod/MvcDynamicDropdownList

The Index View used in the MVC routing implements the complete view with a partial view which will be asynchronously updated on certain input value changes. The Javascript code uses jQuery. Because the partial view DOM elements are reloaded after each change, the on function is used to define the change events, so that it will work after a partial update.

When the ajax request returns, it adds the result to the DOM element with the id = ‘partial’. The change events are added to all child elements, with the id = ‘updateevent’. This could be changed, depending on how you want to find the DOM input elements.

The partial view is updated inside a form. The form is used to do a create request, which updates the whole view. The Javascript requests only updates the partial view, with the new model values depending on the business requirements, which are implemented in the server side code.

@using  AspNetCoreMvcDynamicViews.Models
@model ConfigureSectionsModel
@{
    ViewData["Title"] = "Configure View";
}

<div style="padding:20px;"></div>

@section Scripts{
    <script language="javascript">

        $(function () {
            $('#partial').on('change', '.updateevent', function (el) {
                $.ajax({
                    url: window.location.origin + "/Configure/UpdateViewData",
                    type: "post",
                    data: $("#partialform").serialize(), 
                    success: function (result) {
                        $("#partial").html(result);
                    }
                });
            });
        });

    </script>
}

<form id="partialform" asp-controller="Configure" asp-action="Create" method="post">
    <div class="col-md-12">
        <div id="partial">
            <partial name="PartialConfigure" model="Model.ConfigueSectionAGetModel" />
        </div>

        <div class="form-group row">
            <button class="btn btn-primary col-sm-12" type="submit">Create</button>
        </div>
    </div>
</form>

The partial view is a simple ASP.NET Core view. The model values are used here, and the id values are added to the DOM elements for the jQuery Javascript code. This is then reloaded with the correct values on each change of a DOM element with the id = ‘updateevent’.

@using AspNetCoreMvcDynamicViews.Views.Shared.Components.ConfigueSectionA
@model ConfigueSectionAGetModel

<div class="form-group row">
    <label class="col-sm-5 col-form-label font-weight-bold">LengthA</label>
    <input class="col-sm-5 form-control updateevent" asp-for="LengthA" type="number" min="5" max="400" />
</div>

<div class="form-group row">
    <label class="col-sm-5 col-form-label font-weight-bold">@Model.LengthB</label>
    <input class="col-sm-5 form-control updateevent" asp-for="LengthB" type="number" min="5" max="400" />
</div>

<div class="form-group row">
    <label class="col-sm-5 col-form-label font-weight-bold">LengthAB</label>
    <label class="col-sm-5 form-control ">@Model.LengthAB</label>
    <input readonly asp-for="LengthAB" value="@Model.LengthAB"  type="hidden" />
</div>

<div class="form-group row">
    <label class="col-sm-5 col-form-label font-weight-bold">PartType</label>
    <select class="col-sm-5 form-control updateevent" asp-items="Model.PartTypeItems" asp-for="PartType" type="text"></select>
</div>

The MVC controller implements the server code for view requests. The UpdateViewData action method calls the business logic for updating the input values.

/// <summary>
/// async partial update, set your properties here
/// </summary>
/// <param name="configueSectionAGetModel"></param>
/// <returns></returns>
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult UpdateViewData(ConfigueSectionAGetModel configueSectionAGetModel)
{
	_configureService.UpdateLengthA_LengthB(configueSectionAGetModel);
	_configureService.UpdateSelectType(configueSectionAGetModel);
	return PartialView("PartialConfigure", configueSectionAGetModel);
}

The ConfigureController class implements the action methods to support get, update and create requests.

public class ConfigureController : Controller
{
	private readonly ConfigureService _configureService;

	public ConfigureController(ConfigureService configureService)
	{
		_configureService = configureService;
	}

	/// <summary>
	/// Get a new object, used for the create
	/// </summary>
	/// <returns></returns>
	[HttpGet]
	public IActionResult Index()
	{
		return View(_configureService.GetDefaultModel());
	}

	/// <summary>
	/// create a new object
	/// </summary>
	/// <param name="configueSectionAGetModel"></param>
	/// <returns></returns>
	[HttpPost]
	[ValidateAntiForgeryToken]
	public IActionResult Create(ConfigueSectionAGetModel configueSectionAGetModel)
	{
		var model = new ConfigureSectionsModel
		{
			ConfigueSectionAGetModel = configueSectionAGetModel
		};

		if (ModelState.IsValid)
		{
			var id = _configureService.AddConfigueSectionAModel(configueSectionAGetModel);
			return Redirect($"Update/{id}");
		}

		return View("Index", model);
	}

Build and run the application and the example can be called using:

https://localhost:44306/Configure

Links:

https://docs.microsoft.com/en-us/aspnet/core/mvc/overview?view=aspnetcore-2.1

https://dotnetthoughts.net/jquery-unobtrusive-ajax-helpers-in-aspnet-core/

Handle Ajax Requests in ASP.NET Core Razor Pages

9 comments

  1. […] Updating part of an ASP.NET Core MVC View which uses Forms (Damien Bowden) […]

  2. Hey Damien, Very Interesting, Good Job and Thanks for sharing such a good blog on Updating part of an ASP.NET Core MVC View which uses Forms. Please keep sharing more information and guide students to get more update. keep it up!

    1. Thanks, I have another example in the making which improves this a bit, will publish it soon

  3. […] Updating part of an ASP.NET Core MVC View which uses Form Source: ASP.NET Daily Articles […]

  4. Vinnie Hsu · · Reply

    Is it called PJAX sometimes for this technique?

  5. When the field triggers the event, the inputs focus is lost. For example if I am in the 2nd box, I change the value and press tab then the focus gets lost. Normally it would jump to the PartType field. Is there a way to prevent this?

  6. Dimitris · · Reply

    Enlightening. I wish I had read it years ago. I agree with @Joe’s comment: the focus is lost when navigating away from the inputs by pressing tab. And there is a typo in the naming of the ConfigureSectionAGetModel class in github. One question: does all this apply to core 3.1 as well? or the code can/should be updated somehow?

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.