Updating a Partial View in MVC 5 - javascript

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!

Related

How to receive IEnumerable<int> from client? [duplicate]

This question already has answers here:
Pass an array of integers to ASP.NET Web API?
(18 answers)
Closed 3 years ago.
I have the following code. I'd like to do away with ContactIdsString, but I don't then know how to send the int[] in JavaScript to an IEnumerable in C#. Is there any way?
Html:
#model MyNamespace.Models.MassMailViewModel
#section scripts
{
#Scripts.Render("~/bundles/mass-mail")
<script>
var contactIdsName = '#nameof(MassMailViewModel.ContactIdsString)'
</script>
}
#using (Html.BeginForm(nameof(MassMailController.SendMail), "MassMail", FormMethod.Post, new { id = "massMailForm" }))
{
#(Html.Kendo().Button()
.Name("massMailButton")
.Content("Send")
.HtmlAttributes(new { type = "submit" })
)
#Html.HiddenFor(m => m.ContactIdsString)
...bunch of code for contact-mass-mail-grid...
}
JavaScript:
window.jQuery(function () {
window.jQuery("#massMailForm").submit(function () {
var ids = $('#contact-mass-mail-grid').data('kendoGrid').selectedKeyNames();
var idsJson = JSON.stringify(ids);
var hiddenField = $('#' + window.contactIdsName);
hiddenField.val(idsJson);
});
});
View Model:
public class MassMailViewModel
{
public string ContactIdsString { get; set; }//TODO I'd like to not have to do this.
public IEnumerable<int> ContactIds => JsonConvert.DeserializeObject<IEnumerable<int>>(ContactIdsString);
}
Controller:
public ActionResult SendMail(MassMailViewModel vm)
{
...
}
It looks like you are stopping the value from being posted back in your javascript here:
window.jQuery("#massMailForm").submit
Since you have the ContactIdsString data hidden within the form here:
#Html.HiddenFor(m => m.ContactIdsString)
Why not just let the form submit by removing the submit event handler?
If you are not wanting to do that you would have to submit the data via an ajax call.
Look here for more ajax info https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX
I'm not actually sure you can accomplish what you want without changing your HTML, and I don't think you show enough of your HTML to know really what would need to be changed. The hidden field is just an input, so you really only have one value you can store in it. I'm not sure the razer engine allows you to go to/from an array in a single input.
But, what you could do low impact is create a new getter and leave the ContactIdsString.
public class MassMailViewModel
{
public string ContactIdsString { get; set; }//TODO I'd like to not have to do this.
public IEnumerable<int> ContactIds => this.ContactIdsString.Split(',').Select(n => int.Parse(n));
}
If you truly wanted to get rid of it entirely you'd have to follow the link for what #Kenneth K. suggests
I think you have a slight misunderstanding of the way that IEnumerable works. IEnumerable is for exposing an enumerator that will act on a set of materialized data. In this case, the data being sent to the server from the client is materialized, so there is no need to attempt to define it with an IEnumerable.
The model binder for ASP.NET MVC will attempt to initialize the values sent though, so just like IEnumerable<int> numbers = new int[]{1,2,3}; will work, so will accepting an array of integers into that IEnumerable.
All you need to do is follow the process of posting an array of integers to the server, which is why this question was closed as a duplicate of a question seeking that answer.

ASP.NET MVC 5 best practise form submit

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

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.

Data Filter - View User Interface

I have an Asp.Net MVC web app that I need to provide a user interface in the view to apply data filters to display a subset of the data.
I like the design of what is used on fogbugz with a popup treeview that allows for the selection of data filters in a very concise manner: http://bugs.movabletype.org/help/topics/basics/Filters.html
My controller's action method has some nullable parameter's for all of the available filters:
public ActionResult EmployeeList(int? empId, int? month, int? year,
string tag1, string tag2 //and others....)
{
//...filter employee list on any existing parameters
return View(viewModel);
}
My intention was whenever a filter was applied by clicking on a link, entering text...that filter would be added to the parameter list and reload the page with the correct data to display.
Looking for some guidance or examples on how to create a filter toolbar or best practices for this type of problem. I haven't been able to find a jquery ui plugin or javascript library to do something similar to this so a little lost on where to start.
Thanks.
I did something similar to this by having a main page containing a number of dropdowns containing the parameter options, then a div that had the resultant set ViewUserControl loaded into it on both page load and on dropdown selection change. The controller for the data, in this case TaskList, just needs to return a normal ActionResult View(newTaskList(data)); Example below.
<script>
$(document).ready(function () {
loadDataSet();
});
function loadDataSet(){
var status = document.getElementById('ddlStatus');
var selectedStatus = status.options[status.selectedIndex].value;
if (status.selectedIndex == 0) selectedStatus = '';
$.post('<%= Url.Action("TaskList") %>', { status: selectedStatus },
function (data) {
$('#divTaskList').html(data);
});
}
</script>
<%= Html.DropDownList("ddlStatus", Model.StatusOptions, null, new { onchange = "javascript:loadDataSet();" })%>
<div id='divTaskList' />

Categories

Resources