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/

http://www.talkingdotnet.com/handle-ajax-requests-in-asp-net-core-razor-pages/

Advertisements

One comment

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: