ASP.NET MVC 5 best practise form submit - javascript

Description:
I have a form for user-friendly input:
But i can't submit form in this way, coz my model for this form action looks like:
public string Title { get; set; } // First input
public string Description { get; set; } // Second input
public string SportsmanId { get; set; } // Not used
public List<WorkoutExerciseParam> WorkoutExerciseParams { get; set; } // Items, combined from list items (show on form screenshot)
public SelectList AvailableSportsmans { get; set; } // Dropdown list
So, if I can't submit, I wrote JS code to construct and post consistent model:
$(document)
.ready(function() {
$("#submit").click(function() {
var exerciseList = [];
/* Assemble exerciseList from OL and UL items */
var title = $("input#Title").val();
var description = $("input#Description").val();
var sportsmanId = $("select#SportsmanId").val();
$.post('#Url.Action("Create", "Workout")',
{
Title: title,
Description: description,
SportsmanId: sportsmanId,
WorkoutExerciseParams: exerciseList
});
});
});
This code works fine, but I can't redirect after the action is done (like when I just submit the form):
Then, I rewrite JS code so, that it constructs a new hidden form with hidden input and submit it. But I don't know how to create the list of inputs (List from first code sample).
Question:
What is the best practice to submit data to ASP.NET Controller's Action throw JS that I can use RedirectToAction() and View() methods?
Do I need construct form (how can I do a list of objects) or how handle RedirectToAction() and View() method in JS?

You should be making a normal submit rather that ajax if you want to redirect (or be able to return the view and display validation errors if ModelState is invalid. There is no point using ajax, since ajax calls do not redirect.
You have not shown how your dynamically generating the inputs associated with your WorkoutExerciseParam collection, but they just need to be named correctly with indexers so that they will be bound by the DefaultModelBinder. The format needs to be
<input name="WorkoutExerciseParams[0].SomeProperty" .... />
<input name="WorkoutExerciseParams[0].AnotherProperty" .... />
<input name="WorkoutExerciseParams[1].SomeProperty" .... />
<input name="WorkoutExerciseParams[1].AnotherProperty" .... />
....
Your can generate this using javascript, but a better solution which gives you string type binding, client side validation for the dynamically added items and the ability to also delete items is to use the BeginCollectionItem() method as discussed in the answers to
Submit same Partial View called multiple times data to
controller?
and
A Partial View passing a collection using the
Html.BeginCollectionItem
helper

Related

C# Blazor Form: What would be the most elegant approach for autocompleting input?

In our previous ASP.NET MVC projects we used to rely on Ajax and jQuery to autocomplete values being inputted in to the form (such as getting a list of staff names to choose from whilst still typing) - pure JavaScript example of this.
I'm now creating a new project from scratch in Blazor Server model (.NET 6), and this last bit of work just doesn't seem to be achievable in an elegant way. Or should I say, it works well for a single field, but the trouble comes the approach should be used for multiple fields on the same page.
So the logic is following:
Make <InputText> control hidden and bound the value to the value in the EF data model.
Add <input> control with unique id and #ref tags and make it call C# autocomplete method
Once the input field is clicked, the C# autocomplete method then calls a JavaScript function using IJSObjectReference, that deals with the autocomplete logic (provides suggested values based on what's been typed in so far)
Once user chooses one of the suggested values (i.e. user name), JavaScript is then returning user ID via JSInvokable method in C#
The JSInvokable C# method then populates the relevant user ID value in the data model, and so this value is then going to be updated in both UI and database via EF.
The approach itself is the same as in the official Blazor documentation and it works, like I said.
However, my issue is making it work in some elegant way for multiple input fields on the same form. Is there even an elegant way to achieve this, if I just want to run a pure JavaScript and not jQuery or Ajax?
The biggest question is how do I make C# side of things to decide which input field relates to which field in the data model, whilst making JavaScript calls in between? I would like to avoid relying on hardcoded strings and naming conventions as well as (ideally) I would like to avoid creating multiple ElementReferences and JSInvokable methods essentially doing the same job.
Or perhaps my choice of pure JavaScript for this kind of task within Blazor project is essentially wrong and there are much better alternatives?
Here's some code excerpts (omitting non-essential parts), that hopefully will make it easier to understand.
HTML:
<div class="form-group">
<label>User</label>
<div class="autocomplete">
<InputText class="form-control" type="hidden" #bind-Value="data.UserId" />
<input id="#string.Format("{0}{1}", "userAutocomplete", autocompleteId)"
type="text"
name="#string.Format("{0}{1}", "userAutocomplete", autocompleteId)"
#onclick="AutocompleteUsers"
#ref="userAutocomplete" />
</div>
</div>
C#:
public Data? data { get; set; }
private ElementReference userAutocomplete;
private DotNetObjectReference<RazorPage>? dotNetHelper;
private IJSObjectReference? autocompletelJSObjectReference;
private string autocompleteId = $"_{Guid.NewGuid().ToString().Replace("-", "")}";
private async Task AutocompleteUsers()
{
try
{
dotNetHelper = DotNetObjectReference.Create(this);
autocompletelJSObjectReference = await JS.InvokeAsync<IJSObjectReference>("import", "./js/autocomplete.js");
await autocompletelJSObjectReference.InvokeVoidAsync("Autocomplete", dotNetHelper, userAutocomplete, userListJSON, autocompleteId);
}
}
[JSInvokable]
public async Task UpdateAutocomplete(string _userId, string _autocompleteId)
{
data.UserId = _userId;
}
JavaScript:
export function Autocomplete(dotNetHelper, inp, userList, autocompleteId)
{
inp.addEventListener("input", function (e)
{
var userListJSON = JSON.parse(userList);
for (i = 0; i < userList.length; i++)
{
var dict = userListJSON[i];
b.addEventListener("click", function (e)
{
inp.value = this.getElementsByTagName("input")[0].value;
dotNetHelper.invokeMethodAsync("UpdateAutocomplete", inp.value, autocompleteId);
});
}
});
}
With Blazor you need to rely less on JavaScript. Often functionality such as Autocomplete have already been implemented in Blazor free UI frameworks. I recommend you choose one as it will save you time and energy.
One of amazing free frameworks that I recommend is MudBlazor. Below is an example of how to implement Autocomplete with this framework such as the one shown in w3schools example you provided.
First you need to have a list of options, this can be a List or Enum
Enum for Countries:
You can get this list from https://gist.github.com/jplwood/4f77b55cfedf2820dce0dfcd3ee0c3ea and change attribute to Display(Name = "country").
public enum Countries
{
[Display(Name = "Afghanistan")] AF = 1,
[Display(Name = "Ă…land Islands")] AX = 2,
[Display(Name = "Albania")] AL = 3,
[Display(Name = "Algeria")] DZ = 4,
[Display(Name = "American Samoa")] AS = 5,
[Display(Name = "Andorra")] AD = 6,
// ...
}
Create Enum extension to get country names:
public static class EnumExtensions
{
public static string GetCountryName(this Countries country)
{
return (country == 0) ? String.Empty :
country.GetType()
.GetMember(country.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
.GetName();
}
}
Page with Autocomplete Field:
#page "/"
#using MudBlazorTemplates2.Enums
#using Microsoft.AspNetCore.Components
#using MudBlazorTemplates2.Extensions
<PageTitle>Index</PageTitle>
<MudForm Model="#location">
<MudAutocomplete T="Countries"
Label="Country"
#bind-Value="location.Country"
For="#(() => location.Country)"
Variant="#Variant.Outlined"
SearchFunc="#Search"
ResetValueOnEmptyText="true"
CoerceText="true" CoerceValue="true"
AdornmentIcon="#Icons.Material.Filled.Search"
AdornmentColor="Color.Secondary"
ToStringFunc="#(c => c.GetCountryName())"/>
</MudForm>
<br/>
<p>You selected :#location.Country.GetCountryName()</p>
#code {
private Location location = new Location();
private async Task<IEnumerable<Countries>> Search(string value)
{
var countries = new List<Countries>();
foreach (Countries country in Enum.GetValues(typeof(Countries)))
countries.Add(country);
if (string.IsNullOrEmpty(value))
return null;
// customize if needed
return countries.Where(c => c.GetCountryName()
.StartsWith(value, StringComparison.InvariantCultureIgnoreCase));
}
public class Location
{
public Countries Country { get; set; }
}
}
Output:
You can find more simpler examples for Autocomplete at https://mudblazor.com/components/autocomplete#usage

Updating a Partial View in MVC 5

I am getting an error when trying to load a partial view that should display a list on the create view of the MVC app. The list is based on a value will come from a list of values drop control.
On create view there is no selection so the list is empty and will need to refreshed after the user selects a value while in the MVC create view.
I followed the accepted answer on this question and got errors:
Updating PartialView mvc 4
But I have some questions about what is being said.
Someone said: "There are some ways to do it. For example you may use jQuery:" and he shows the Java query.
But he also shows another method and says: "If you use logic in your action UpdatePoints() to update points"
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}
I get the following error
The parameters dictionary contains a null entry for parameter 'ID' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult UpdateList(Int32)' in 'System.Controllers.RController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
I have no clue what this error means
So in create view:
<div class="col-sm-6">
<div class="form-horizontal" style="display:none" id="PVList">
#{ Html.RenderAction("UpdateList");}
</div>
</div>
In controller under the create action as its own function
[HttpGet]
public ActionResult UpdateList(int ID)
{
if (ID != 0)
{
ViewBag.List = Get_List(ID);
return PartialView("PV_List");
}
else
{
ViewBag.List = "";
return PartialView("");
}
}
And the function that makes the list for the view bag function:
private List<SQL_VIEW_LIST> Get_List(int ID)
{
return db.SQL_VIEW_LIST.Where(i => i.ID == ID).ToList();
}
The JavaScript for the for the list of values drop down list of values: That also controls turning on the visibility of the list when it has data:
//Fire The List to make visible after list values select
$(document).ready(function () {
$('#RES_VEH_ID').change(function ()
{
$("#PV_List").show(); // Shows Edit Message
$.post('#Url.Action("PostActionTo_Partial","Create")').always(function()
{ ('.target').load('/Create'); })
});
})
Also does anyone know what this string mean: ? "PostActionTo_Partial"
Also does anyone know what this means ViewBag.points = _Repository.Points; I get the view bag part but it's the _Repository.Points; part that I don't understand. Any one have any ideas of what is going on there?
I can't understand what do you try to do. But i'll try to answer.
I have no clue what this error means.
This error means that model binder can't find parameter "ID" for action method
public ActionResult UpdateList(int ID)
Because you don't send any parameter for this method:
You can try this:
#{ Html.RenderAction("UpdateList", new {ID="value"});}
Or you can set default value in your method:
public ActionResult UpdateList(int ID=value)
or make "ID" nullable:
public ActionResult UpdateList(int? ID)
Also does anyone know what this string mean: ? "PostActionTo_Partial"
this is "action name" in yor controller
Also does anyone know what this means ViewBag.points =
_Repository.Points;
it means assigning dynamic object "VivBag.points' data to transfer them into view
So with help from Matt Bodily You can Populate a Partial View in the create view triggered by a changed value in a drop down list using a view
bag and something called Ajax. Here is how I made my code work.
First the partial view code sample you need to check for null data
_WidgetListPartial
#if (#ViewBag.AList != null)
{
<table cellpadding="1" border="1">
<tr>
<th>
Widget Name
</th>
</tr>
#foreach (MvcProgramX.Models.LIST_FULL item in #ViewBag.AList)
{
<tr>
<td>
#item.WidgetName
</td>
</tr>
}
</table>
}
Populating your View Bag in your controller with a function
private List<DB_LIST_FULL> Get_List(int? VID)
{
return db.DB_LIST_FULL.Where(i => i.A_ID == VID).ToList();
}
In your Create controller add a structure like this using the [HttpGet] element
this will send you data and your partial view to the screen placeholder you have on your create screen The VID will be the ID from your Drop
down list this function also sends back the Partial View back to the create form screen
[HttpGet]
public ActionResult UpdatePartialViewList(int? VID)
{
ViewBag.AList = Get_List(VID);
return PartialView("_WidgetListPartial",ViewBag.AList);
}
I am not 100% if this is needed but I added to the the following to the ActionResult Create the form Id and the FormCollection so that I could
read the value from the drop down. Again the Ajax stuff may be taking care if it but just in case and the application seems to be working with
it.
This is in the [HttpPost]
public ActionResult Create(int RES_VID, FormCollection Collection, [Bind(Include = "... other form fields
This is in the [HttpGet] again this too may not be needed. This is reading a value from the form
UpdatePartialViewList(int.Parse(Collection["RES_VID"]));
On Your Create View Screen where you want your partial view to display
<div class="col-sm-6">
<div class="form-horizontal" style="display:none" id="PV_WidgetList">
#{ Html.RenderAction("UpdatePartialViewList");}
</div>
</div>
And finally the Ajax code behind that reads the click from the dropdown list. get the value of the selected item and passed the values back to
all of the controller code behind to build the list and send it to update the partial view and if there is data there it pass the partial view
with the update list to the create form.
$(document).ready(function () {
$('#RES_VID').change(function ()
{
debugger;
$.ajax(
{
url: '#Url.Action("UpdatePartialViewList")',
type: 'GET',
data: { VID: $('#RES_VID').val() },
success: function (partialView)
{
$('#PV_WidgetList').html(partialView);
$('#PV_WidgetList').show();
}
});
This many not be the best way to do it but this a a complete an tested answer as it work and it is every step of the process in hopes that no
one else has to go through the multi-day horror show I had to go through to get something that worked as initially based on the errors I thought
this could not be done in mvc and I would have to continue the app in webforms instead. Thanks again to everyone that helped me formulate this
solution!

ViewModel current state to JSON

I have an issue with aps.net mvc project. I have a view where is set list of check boxes inside of begin form, then on submit appropriate fields are shown as a report. So I have to add a button to my view, where user is setting which fields he d like to see, so as he could save all checkbox values as a preset with its name.
I have model with a lot of nested models it looks like this:
public class EmployeeOverallReport
{
public List<PersonalData> ListOfPersonalData { get; set; }
public EmployeeOverallReportBool ColumnsNeeded { get; set; }
public EmployeeOverallReportFilters ModelFilters { get; set; }
}
I actually need ColumnsNeeded model, which has alot of bool properties for storing each checkbox value (true/false).
So on click I have to get current state of checkboxes and make a post with these model values.
I have been trying to serialize my form:
var data = $('#myForm').serialize();
$.post(url, { presetName: Name, entry: data}, function (data) {
$("#saveResult").html("Saglabats");
});
I got JSON string but it was invalid and i could not deserialize it back.
Here is what I am trying to do now:
$("#savePresetButton").on('click', function () {
var url = "/Reports/SavePreset";
var data = #Html.Raw(Json.Encode(Model));
$.post(url, { presetName: Name, entry: data}, function (data) {
$("#saveResult").html("Saglabats");
});
});
this code is using my viewModel with its properties, where all ColumnsNeeded properies are set to false, as it is by default and all user side changes in a view are not set to model yet, so as my form was not submitted and values were not changed.
How could I get current state of all checkboxes on user side?
Not doing it like :
var dataset = {
CategoryBool: $("#ColumnsNeeded_CategoryBool").val(),
NameBool: $("#ColumnsNeeded_NameBool").val(),
KnowledgeLevelBool: $("#ColumnsNeeded_KnowledgeLevelBool").val(),
SkillAdditionalInfoBool: $("#ColumnsNeeded_SkillAdditionalInfoBool").val(),
...
}
because I have more than 90 properties there..
I am sorry for this post, but posting some code is impossible due to count of properties inside the model.
Could you serialize the entire form and ajax submit the form itself?
see: Pass entire form as data in jQuery Ajax function

How to append Complex Data Type to View Model before submit of form post method

I am using Form Post method to submit data to controller in my MVC application.
My MVC Application controller method accepting ViewModel.
I have added new list of other viewModel and I want to pass the data to that newly added viewmodel.
Sample Code ( not fully executed )
Controller Existing Code
public ActionResult AddProduct(ProductViewModel productViewModel)
{
//some operation
}
public class ProductViewModel
{
Branch_Product_Taxes = new List<Branch_Product_TaxesViewModel>();
}
//viewmodel
$('#ProductForm').submit(); //javascript form submit method
var ObjectList = new Array()
Now I have added List of Objects in Object List
I want to pass this list controller
You need to create hidden elements as per your complex data type
Consider following issue
If you need to post employee list with attribute like name etc then go through following code.
Your view Model something like
public class ProductViewModel
{
public IList<Employees> = new List<Employees>();
}
Javascript Code
var html = '<input type="hidden" name="Employees[0].Name" value="Employee1"/>';
html+='<input type="hidden" name="Employees[0].Designation" value="Des1"/>';
html+='<input type="hidden" name="Employees[1].Name" value="Employee2"/>';
html+='<input type="hidden" name="Employees[1].Designation" value="Des2"/>';
$('#ProductForm').append(html);
$('#ProductForm').submit();
You will get list of two records as (0 and 1 ) index.
You can use for loop and generate hidden html dynamically and append it before Form submit.
you need to define the list as property inside the ViewModel you are passing, by default modelbinder does not consider the fields like
Branch_Product_Taxes = new List<Branch_Product_TaxesViewModel>();
you need to define the property Like
public IList<Branch_Product_TaxesViewModel> Branch_Product_Taxes { get; set; }

How do I filter the Model based on the value of a textbox using Javascript (Razor)

this question may be totally non-sense but I am new in MVC and Razor.
Here is what I am trying to do:
I have a simple table "Products" from where I retrrieve all the
values using my model. The products table has a field Id, Name,
Price and StartDate.
I am passing the data from the Controller to
the view as a List
In the view I have an AutoComplete field (KendoUI) where I type the
name of the product
In the event handler
of the AutoCoplete change event, I want to retrieve the "Price" of
the product that has been typed in the AutoComplete textbox
Below is the code for the Product:
public class Product
{
public int ID { get; set; }
public string Name { get; set; }
public DateTime FirstRelease { get; set; }
public decimal Price { get; set; }
}
public class WidgetsDBContext : DbContext
{
public DbSet<Product> Products { get; set; }
}
The code for my View (partial code) is below:
<div id="auto">
<p>Start typing</p>
<label for="productAutoComplete">Please select procuct:</label>
#(Html.Kendo().AutoComplete()
.Name("productAutoComplete")
.DataTextField("Name")
.BindTo(Model)
.Filter(FilterType.StartsWith)
.Placeholder("Select the product")
.HighlightFirst(true)
.Suggest(true)
)
<script>
function productAutoComplete_change() {
var gauge = $("#linearGauge").data("kendoLinearGauge");
#foreach (var p in Model) <==== HERE I WANT TO DO THE FILTERING
{
#: gauge.value(#p.Price);
}
}
$("#productAutoComplete").bind("change", productAutoComplete_change);
</script>
</div>
CONCERN FOR VALIDATION: If I understand the basics of MVC and Razor well, then am I correct to think that the view is rendered once (during the HTTP GET) and therefore I am not able to dynamically filter the Model in Razor (but only in Javascript)? If yes, then what is the right way to do it?
Thank you in advance
Lefteris
am I correct to think that the view is rendered once (during the HTTP
GET) and therefore I am not able to dynamically filter the Model in
Razor (but only in Javascript)?
Yes, that's correct.
If yes, then what is the right way to do it?
You could use AJAX. For example in the productAutoComplete_change function you could send an AJAX request to a controller action that will perform the filtering and return a partial view containing the filtered results.
There are many tutorials out there about using AJAX with ASP.NET MVC. For example with jQuery you could use the $.ajax() function.

Categories

Resources