Dynamic binding of controls in ASP.Net MVC [duplicate] - javascript

I have added a button in my view. When this button is clicked partial view is added. In my form I can add as much partial view as I can. When Submitting this form data I am unable to send all the partial view data to controller.
I have made a different model having all the attributes and I have made a list of that model to my main model. Can anyone please give me some trick so that I can send all the partial view content to my controller?
In My View
<div id="CSQGroup">
</div>
<div>
<input type="button" value="Add Field" id="addField" onclick="addFieldss()" />
</div>
function addFieldss()
{
$.ajax({
url: '#Url.Content("~/AdminProduct/GetColorSizeQty")',
type: 'GET',
success:function(result) {
var newDiv = $(document.createElement("div")).attr("id", 'CSQ' + myCounter);
newDiv.html(result);
newDiv.appendTo("#CSQGroup");
myCounter++;
},
error: function(result) {
alert("Failure");
}
});
}
In My controller
public ActionResult GetColorSizeQty()
{
var data = new AdminProductDetailModel();
data.colorList = commonCore.getallTypeofList("color");
data.sizeList = commonCore.getallTypeofList("size");
return PartialView(data);
}
[HttpPost]
public ActionResult AddDetail(AdminProductDetailModel model)
{
....
}
In my Partial View
#model IKLE.Model.ProductModel.AdminProductDetailModel
<div class="editor-field">
#Html.LabelFor(model => model.fkConfigChoiceCategorySizeId)
#Html.DropDownListFor(model => model.fkConfigChoiceCategorySizeId, Model.sizeList, "--Select Size--")
#Html.ValidationMessageFor(model => model.fkConfigChoiceCategorySizeId)
</div>
<div class="editor-field">
#Html.LabelFor(model => model.fkConfigChoiceCategoryColorId)
#Html.DropDownListFor(model => model.fkConfigChoiceCategoryColorId, Model.colorList, "--Select Color--")
#Html.ValidationMessageFor(model => model.fkConfigChoiceCategoryColorId)
</div>
<div class="editor-field">
#Html.LabelFor(model => model.productTotalQuantity)
#Html.TextBoxFor(model => model.productTotalQuantity)
#Html.ValidationMessageFor(model => model.productTotalQuantity)
</div>

Your problem is that the partial renders html based on a single AdminProductDetailModel object, yet you are trying to post back a collection. When you dynamically add a new object you continue to add duplicate controls that look like <input name="productTotalQuantity" ..> (this is also creating invalid html because of the duplicate id attributes) where as they need to be <input name="[0].productTotalQuantity" ..>, <input name="[1].productTotalQuantity" ..> etc. in order to bind to a collection on post back.
The DefaultModelBinder required that the indexer for collection items start at zero and be consecutive, or that the form values include a Index=someValue where the indexer is someValue (for example <input name="[ABC].productTotalQuantity" ..><input name="Index" value="ABC">. This is explained in detail in Phil Haack's article Model Binding To A List. Using the Index approach is generally better because it also allows you to delete items from the list (otherwise it would be necessary to rename all existing controls so the indexer is consecutive).
Two possible approaches to your issue.
Option 1
Use the BeginItemCollection helper for your partial view. This helper will render a hidden input for the Index value based on a GUID. You need this in both the partial view and the loop where you render existing items. Your partial would look something like
#model IKLE.Model.ProductModel.AdminProductDetailModel
#using(Html.BeginCollectionItem())
{
<div class="editor-field">
#Html.LabelFor(model => model.fkConfigChoiceCategorySizeId)
#Html.DropDownListFor(model => model.fkConfigChoiceCategorySizeId, Model.sizeList, "--Select Size--")
#Html.ValidationMessageFor(model => model.fkConfigChoiceCategorySizeId)
</div>
....
}
Option 2
Manually create the html elements representing a new object with a 'fake' indexer, place them in a hidden container, then in the Add button event, clone the html, update the indexers and Index value and append the cloned elements to the DOM. To make sure the html is correct, create one default object in a for loop and inspect the html it generates. An example of this approach is shown in this answer
<div id="newItem" style="display:none">
<div class="editor-field">
<label for="_#__productTotalQuantity">Quantity</label>
<input type="text" id="_#__productTotalQuantity" name="[#].productTotalQuantity" value />
....
</div>
// more properties of your model
</div>
Note the use of a 'fake' indexer to prevent this one being bound on post back ('#' and '%' wont match up so they are ignored by the DefaultModelBinder)
$('#addField').click(function() {
var index = (new Date()).getTime();
var clone = $('#NewItem').clone();
// Update the indexer and Index value of the clone
clone.html($(clone).html().replace(/\[#\]/g, '[' + index + ']'));
clone.html($(clone).html().replace(/"%"/g, '"' + index + '"'));
$('#yourContainer').append(clone.html());
}
The advantage of option 1 is that you are strongly typing the view to your model, but it means making a call to the server each time you add a new item. The advantage of option 2 is that its all done client side, but if you make any changes to you model (e.g. add a validation attribute to a property) then you also need to manually update the html, making maintenance a bit harder.
Finally, if you are using client side validation (jquery-validate-unobtrusive.js), then you need re-parse the validator each time you add new elements to the DOM as explained in this answer.
$('form').data('validator', null);
$.validator.unobtrusive.parse($('form'));
And of course you need to change you POST method to accept a collection
[HttpPost]
public ActionResult AddDetail(IEnumerable<AdminProductDetailModel> model)
{
....
}

Related

Use MVC Session to store Client-side values (e.g. filter text) between visits

In an MVC View, is there an efficient way to store client-side values for use on subsequent page visits?
Typical scenario
An Index page has a table that's getting a bit long so I add a filter (I know paging is another option) and use an input control with some JavaScript to limit the table rows without having to perform another "Get" from the server.
This works fine but, if I navigate off (say) into an edit page then return back to the Index page, the filter is clearly no longer there.
After a bit of searching I never found anything simple so I post my meagre answer below.
The View contains a form at the top of the page into which a user can type filter text (on form "Get", text is set from a session value):-
<form id="frmEdit">
#Html.AntiForgeryToken()
<div class="form-group row">
<div class="col-sm-6">
#Html.ActionLink("Create New", "Create", null, new { #class = "nav-item nav-link" })
</div>
<label for="search" class="col-sm-2 col-form-label text-right">Filter</label>
<div class="col-sm-4">
<input type="text" placeholder="Filter" class="form-control" id="search" value=#Session["SparesSectionFilter"]>
</div>
</div>
</form>
A script section contains the filtering JavaScript but also a postback to the controller
#section Scripts{
<script type="text/javascript">
// on load
PerformFilter();
// hook up events
$(function () {
$("input#search").on("keydown keyup", function () {
PerformFilter();
// post back to session for reuse
$.post('SparesSections/Session_Add', { __RequestVerificationToken: $('[name=__RequestVerificationToken]').val(), itemName: 'SparesSectionFilter', itemValue: $("#search").val() });
});
})
</script>
}
I have a custom base-class for my controller into which I've added the following actions. These are usable from any controller using this class. The Razor view loads the session value but I've included a "Get" in the controller for client-side options.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Session_Add(string itemName, string itemValue)
{
Session.Add(itemName, itemValue);
return Json(new { itemName = itemName, itemValue = itemValue }, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult Session_Get(string itemName)
{
return Json(new { itemName = itemName, itemValue = Session[itemName] ?? string.Empty }, JsonRequestBehavior.AllowGet);
}

Pass complex objects using ajax MVC

I have a view with multiple sections. i would like to update sections individually using partial views and ajax.
I have this so far:
Controller:
[HttpPost]
public PartialViewResult userdetailssettings(UserDetails model)
{ .... }
View Html:
<div id="userDetailsPartial">
#Html.Partial("_user_details", Model.userdetails)
</div>
Partial Html:
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(x => x.Forename, new { #class = "form-control", placeholder = "Enter your forename" })
#Html.ValidationMessageFor(x => x.Forename)
</div>
</div>
<div class="form-group">
<div class="col-md-12">
#Html.TextBoxFor(x => x.Surname, new { #class = "form-control", placeholder = "Enter your surname" })
#Html.ValidationMessageFor(x => x.Surname)
</div>
</div>
Javascript on View:
var detailsUrl = "#Url.Action("userdetailssettings", "UserLogin")";
var detailsmodel = JSON.stringify(#Html.Raw(Json.Encode(#Model.userdetails)));
$(document).on('click touchstart', '#saveDetails', function () {
$.ajax({
type: "POST",
dataType: 'json',
data: detailsmodel,
url: detailsUrl,
contentType: "application/json"
}).done(function (res) {
$("#userDetailsPartial").html(res);
addresssearch();
});
});
The model is being passed to the controller by the ajax, however the values are not that of the inputs. They are the original values passed from the controller to open the view.
I have tried wrapping the partial in tags and also tried adding form tags inside the partial.
I have also tried putting this code:
var detailsUrl = "#Url.Action("userdetailssettings", "UserLogin")";
var detailsmodel = JSON.stringify(#Html.Raw(Json.Encode(#Model.userdetails)));
Inside the click function.
Nothing I do passes the updated values from the inputs.
I have thought of creating a new instance of the model from the inputs in the javascript i.e.
var detailsmodel = [ { Forename: $('#Forename').val(), Surname: $('#Surname').val() } ];
But if I am just creating json why can I not just convert the bound model to json.
why can I not just convert the bound model to json
This is because you are using MVC, not MVVM.
The "bound model" is one way from the controller to the view via the model; it's possible you're mixing the term "bound model" with "model" and "binding".
If you POST the form, you'll get the model in the Action (based on parameters of course), but if you pass via ajax, you'll need to get the current values from the form (as in your comment 'creating a new instance of the model from the inputs').
You can generate data to pass via AJAX in various ways, such as:
var data = $("form").serialize();
rather than adding every input manually.
var detailsmodel = JSON.stringify... is set when the view is generated and will not change automatically using MVC.
That's because the data you're passing is statically set at page load, based on #Html.Raw(Json.Encode(#Model.userdetails)).
You would need to use something like $form.serialize(), or otherwise create the post body from the actual fields on the page.

Bind Data Of a span to database with ASP MVC,Uses Model Binder

I'm new in Asp.net MVC
I need some suggestions for how to make a counter then give the value of it to model binder.
I have two modal Pages.in the first one I have this counter for users to choose the number of their request it's like this :
when user click on plus icon the number changed By Javascript
when user click on next button , the next modal page shows, which I have selecteddate and number of travelers there by javascript. and also a form which I want model binder to make an object of it.
here is the view of my next modal page in summary
<p>
<span id="selecteddate"></span>
<span id="selectedcount"></span>
<span id="selectedprice"></span>
</p>
and here is javascript :
$(".nextbtn").click(function () {
$("#selecteddate").html("Selected Date is : "+$("#showdate").html());
$("#selectedprice").html("Total Price is : " + $("#tpriceforall").html());
$("#selectedcount").html($("#shownum").html());
});
and it works correctly.
and also I have a Form in this next modal page too . I want to pass input data of users to data base + the number which is available in span #selectedcount that java script set it each time .
as I want to use ModelBinder , there is an input which it would be hidden.
but just to pass data . here is the input for TravelersCount of my Request Model
<div class="form-group">
#Html.LabelFor(model => model.Request.TravelersCount, htmlAttributes: new {#class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Request.TravelersCount, new { htmlAttributes = new { #class = "form-control", #*#Value=?????*# } })
#Html.ValidationMessageFor(model => model.Request.TravelersCount, "", new { #class = "text-danger" })
</div>
</div>
What Should I write for Value in the EditorFor?
Or if this way is completely irregular please suggest me new one.
Really appreciate you'r help. thanks
Your EditorFor() method creates an input with id="Request_TravelersCount".
To update its value when the button is clicked, you can use
$(".nextbtn").click(function () {
$("#selecteddate").html("Selected Date is : "+$("#showdate").html());
$("#selectedprice").html("Total Price is : " + $("#tpriceforall").html());
var num = $("#shownum").html();
$("#selectedcount").html(num);
$('#Request_TravelersCount').val(num);
});
Side note: You should not attempt to set the value attribute in a HtmlHelper method (the method will set the correct value taking into account ModelState values)

HTML form submit a single item from a collection

I have a partial view with a view model that has a collection of sellers. I loop over all of the sellers to render the list. Here is the view model:
public class SellersPartialViewModel
{
public IList<OrderViewModel> Sellers { get; set; }
}
In the partial view I'm using Html.BeginCollectionItem("Sellers") when I loop through the collection and here is my code for the partial (FYI I've stripped away a lot of useless code that doesn't need to be seen):
<div id="sellers-list">
#{
var i = 0;
while (i < Model.Sellers.Count) {
var seller = Model.Sellers[i];
using (Ajax.BeginForm(MVC.Video.PurchaseShares(), purchaseSharesAjaxOptions, new { #class = "seller-form", id = "seller-form-" + i })) {
#using(Html.BeginCollectionItem("Sellers")) {
#Html.TextBoxFor(m => seller.Qty, new { #class = "buyer-qty" })
#Html.ValidationMessageFor(m => seller.Qty)
<input class="buyer-qty-submit" name="Qty" type="hidden" value="" />
<button type="submit">Buy</button>
}
}
}
i++;
}
}
</div>
This works fine for rendering the partial and getting the client-side validation working
however I want each seller to have the inputs named qty and orderId for a controller action called PurchaseShares(int orderId, int qty).
The only problem is the form is being submitted with the odd GUID like Sellers[5b5fd3f2-12e0-4e72-b289-50a69aa06158].seller.Qty which I understand is correct for submitting collections but I don't need to do that.
Right now I have some Javascript that is updating the class="buyer-qty" with whatever they select and it works fine but there has got to be a better way of doing this, no?
Thanks
Why are you using the Html.BeginCollectionItem helper if you don't want to submit collections?
You could have a partial representing your Order collection item (_Order.cshtml):
#model OrderViewModel
#Html.TextBoxFor(m => m.Qty, new { #class = "buyer-qty" })
#Html.ValidationMessageFor(m => m.Qty)
And in your main view simply loop through your collection property and render the partial for each element:
#model SellersPartialViewModel
<div id="sellers-list">
#foreach (var seller in Model.Sellers)
{
using (Ajax.BeginForm(MVC.Video.PurchaseShares(), purchaseSharesAjaxOptions, new { #class = "seller-form" }))
{
#Html.Partial("_Order", seller)
<button type="submit">Buy</button>
}
}
</div>
Now your controller action you are submitting to could directly work with the corresponding view model:
[HttpPost]
public ActionResult PurchaseShares(OrderViewModel order)
{
...
}
because:
[HttpPost]
public ActionResult PurchaseShares(int orderId, int qty)
{
...
}
kinda looks uglier to me but it would also work if you prefer it.
Also please notice that I have deliberately removed the Qty hidden field shown in your code as it would conflict with the input element with the same name. Also don't forget to include an input field for the orderId argument that your controller action is expecting or when you submit it could bomb. Also you could send it as part of the routeValues argument of the Ajax.BeginForm helper if you don't want to include it as an input field.

Add Elements to Form Dynamically with JS

I have created 15 fields in my MySQL Table and would like to give the end user the option of using a form to add up to that many items. However, to keep the interface clean, I would like to only present them with maybe 2-3 Textboxes and give them a button that would allow them to add more should they need it.
I don't believe adding the textboxes to the form using Javascript would be an issue, but I am confused as to how to process it exactly once I have submitted the POST Data to the form handler. Can anyone shed some light on the best way to go about this?
If you have to use a normal POST variable containing all the form values, you should be able to do something like this:
When generating the textboxes with the server language and/or javascript, the way they are sent to the server is with their name attribute. If you provide a consistent way of naming the elements, you can "combine" things with numbers. For example, if you provide 2 textboxes every time the user clicks "Add" (one for "foo" and one for "bar"), then you can increment the number at the end to make sure they match.
<input type="text" name="foo1" /><input type="text" name="bar1" />
<input type="text" name="foo2" /><input type="text" name="bar2" />
and so on
Then on the server, you need to find every item in the POST variable that starts with "foo" and "bar"
for (item in POST) {
if (item startswith "foo") {
// Extract the number at the end, and find the related "bar"
}
}
Assuming that you are using ASP.NET MVC for web application, along with jQuery for client side framework.
Let's more assume that you have a model like this:
public class Gift
{
public string Name { get; set; }
public double Price { get; set; }
}
Your initial action and data could be like this:
public ActionResult Index()
{
var initialData = new[] {
new Gift { Name = "Tall Hat", Price = 39.95 },
new Gift { Name = "Long Cloak", Price = 120.00 },
};
return View(initialData);
}
Whereas, your view could be this:
<h2>Gift List</h2>
What do you want for your birthday?
<% using(Html.BeginForm()) { %>
<div id="editorRows">
<% foreach (var item in Model)
Html.RenderPartial("GiftEditorRow", item);
%>
</div>
<input type="submit" value="Finished" />
<% } %>
And partial view for gift editor could be this:
<div class="editorRow">
<% using(Html.BeginCollectionItem("gifts")) { %>
Item: <%= Html.TextBoxFor(x => x.Name) %>
Value: $<%= Html.TextBoxFor(x => x.Price, new { size = 4 }) %>
<% } %>
</div>
The key is "BeginCollectionItem" helper method, which is not standard in ASP.NET MVC. It will generate some keys for variable length models. I will add a link to files later.
Your Handler would be like this:
[HttpPost]
public ActionResult Index(IEnumerable<gift> gifts)
{
// To do: do whatever you want with the data
}
You get a list of gifts with this approach, filled with values in textboxes.
To add one more item, you need to send an ajax request to this view:
Hope it helps
Source: http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
Download: http://blog.codeville.net/blogfiles/2010/January/ListEditorDemo.zip

Categories