knockoutmvc - unable to parse bindings - asp.net-mvc

I have an ASP.NET MVC site and I am trying to get knockout-mvc working with it.
I have created a View Model in the C# code called Refund that contains among other things a Voucher called Vouchertype and a List<Country> called Countries. Voucher has a variable of type int called VoucherNumber
This View Model is passed into a strongly defined view Refund\Index
I am trying to get knockout-mvc to bind the values in Refund.Voucher.VoucherNumber to a textbox, and the Values in Refund.Countries to a drop-down list. On the controller I have hardcoded the values of Voucher.Vouchernumber and added two countries to the Country list.
Here is my View Code:
#using Resources
#using PerpetuumSoft.Knockout
#model MVC.Models.RefundViewModel
#{
var ko = Html.CreateKnockoutContext();
}
<div id="refundformcontainer">
<div id="headersection">
<div id="pagetitlecontainer">#Language.RefundVouchers</div>
<div id="helpercontainer">
<label id="lblhelper">To begin enter a voucher number or scan a barcode</label>
</div>
</div>
<div id="vouchercontainer">
<div id="voucherdetailscontainer">
<h5>#Language.VoucherDetails</h5>
<div id="vouchernumbercontainer" class="initialvoucherfield">
#Html.LabelFor(x=>x.Voucher.VoucherNumber)
#ko.Html.TextBox(x=>x.Voucher.VoucherNumber)
</div>
<div id="countrycontainer" class="initialvoucherfield">
#Html.LabelFor(x=>x.Voucher.Country)
<select ko.Bind.Options(x=>x.Countries).OptionsText("Name").OptionsValue("CountryId").Value(x=>x.Voucher.CountryId) ></select>
</div>
</div>
</div>
</div>
#ko.Apply(Model);
When the page loads, neither controls are bound to.
When I look at the generated source the following code is generated
<script type="text/javascript">
var viewModelJs = {"Refund":null,"Voucher":{"VoucherId":0,"VoucherNumber":123456789,"Country":null,"CountryId":0,"Retailer":null,"RetailerId":0,"PurchaseDate":"0001-01-01T00:00:00","CustomsStampDate":null,"InvoiceNumber":"","LineItems":[],"TotalPurchasePrice":0.0},"Countries":[{"CountryId":380,"Name":"Italy"},{"CountryId":724,"Name":"Spain"}]};
var viewModel = ko.mapping.fromJS(viewModelJs);
ko.applyBindings(viewModel);
</script>
knockout-2.2.0.js and knockout.mapping-latest.js are both included in the page
The error I am getting is
0x800a139e - JavaScript runtine error: Unable to parse bindings
Message: [Object Error]
Bindings value: Voucher().VoucherNumber
I then changed the Refund View model so it had a property VoucherNumber and had the textbox reference this instead of the Voucher.VoucherNumber property
#ko.Html.TextBox(x=>x.VoucherNumber)
When I ran this I got the same unable to parse bindings error, but this time for the country
Bindings value: options : Countries, optonsText : Name, optionsValue : CountryId
Does anybody have any idea what is causing this?

i think, this should work.
<select #ko.Bind.Options(x=>x.Countries).OptionsText("'Name'").OptionsValue("'CountryId'").Value(x=>x.Voucher.CountryId) ></select>

Related

MVC Checkboxes Collection Displays Correctly in View but I on Post Back the Collection is Empty

I am having trouble with a simple Visual Basic Code for MVC using Check Boxes.
I am trying to create a Form where the user could choose which Office Department will have access to a particular Document.
Here is the output in the browser:
The data gets displayed correctly from the Model to Controller to View.
However, I cannot get the clicked values from the View back to the Controller.
Here is the Model:
Public Class Department
<Required>
<Display(Name:="Department ID")>
Public Property DepartmentID As Integer = 1
<Required>
<Display(Name:="Department Name")>
Public Property DepartmentName As String = ""
<Required>
<Display(Name:="Department Image")>
Public Property DeptImage As String = ""
Public Property IsSelected As Boolean = False
End Class
Here is the View
<section class="checkBoxListFor">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Access Rights</h3>
</div>
<div class="panel-body">
#For Each oDept As Department In Model.DeptList
#<text>
#Html.CheckBoxFor(Function(m) oDept.IsSelected)
#oDept.DepartmentName
#Html.HiddenFor(Function(m) oDept.DepartmentID)
#Html.HiddenFor(Function(m) oDept.DepartmentName) <br />
</text>
Next
</div>
</div>
</section>
I have read an article here about NOT using a For Each Loop to display the collection of Form Controls since when you look at the generated HTML Code, the "name" will not be correct and hence it won't bind to the Controller when POST Back is called.
The problem is I do not know how to do it.
Any help is appreciated on how to properly implement this simple task.
Thanks!
Ok, I found the problem.
It is because of the
<fieldset>
</fieldset>
tag.
The checkbox collection loop is outside of these tags.
Although all of the fields and the Check Boxes are under the html helper "BeginForm"
the checkboxes loop is outside of the tag.
This is the reason why these checkbox's values were never passed back to the controller during post back.
I put the loop inside the tag and viola, they are now populated on the "POST" controller.

How to change " asp-action=" with your selected Viewbag .Net Core 2.0

I am trying to change the "asp-action= ", unfortunately I could not find anything on the internet...
Currently I am working with a ViewBag where I can select a value from that list.
What I want is: I want to put that selected value from the ViewBag in the "asp-action= ( here ) "
Image of my index
Image of my Post method
<form method="post" enctype="multipart/form-data" asp-controller="Parser" asp-action= "PostDrone">
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<select asp-items="#(new SelectList(#ViewBag.listofitems ))"></select>
<input type="file" name="files" multiple />
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<input type="submit" value="Upload" />
</div>
</div>
For example:
I want the "asp-action=" have the string value "PostSchoen" if I selected PostSchoen from the viewbag selectlist
I hope it is understandable what i said
What you wants to do it should doing by client side development with JS
But you have three ways:
1) You can change it by using JS
here an example with Jquery
need add it to onReady function this will change action to option val
<script>
$(function() {
$("select").change(function (){
//set form action to option val or get to whatever you need
$(this).closest("form").attr("action",$(this).val());
});
});
</script>
2) Send data to one contoller method then switch it by your select or other options
change in view
<select name="typeOfUploading" asp-items="#(new
SelectList(#ViewBag.listofitems ))"></select>
change in controller
PostDrone(List<IFromFile> files, string typeOfUploading)
{
//and use typeOfUploading this will be selected value from your select list
}
3) Firstly provide for user this data send choise, that generate him correct view with needed action

Handling hidden field in multiple forms in Mvc 4.0

I am having multiple forms in one page and that page inherits one single model.Every form submission requires a common value. So, common value is stored in hidden field. The hidden field is kept global i.e outside of all the forms but my problem is whenever I submit form, that hidden field is coming to be empty.The hidden field is #Html.HiddenfieldFor(m=>m.FkId) and this FkId is of string type proprty in model i.e public string FkId{get;set;} .Can somebody please guide me how to handle this situation. If I keep hidden field in one of the forms then , it is coming in controller but only for that form submission where I have kept it. But I want that property to be set once and can use in all the form submissions.Please help me. How can I sort out this problem
Some related code
<div id="tabs">
<ul>
<li>Nunc tincidunt</li>
<li>Proin dolor</li>
<li>Aenean lacinia</li>
</ul>
<div id="tabs-1">
#using (Ajax.BeginForm("Evaluation","SaveTab1"{new AjaxOptions { Onsucess= "DisplayMessage" }))
{
#Html.HiddenFieldfor(m=>m.fkID)
<input type="Submit" id="btnTab1" value="Submit" onclick="CheckUser();"/>
}
</div>
<div id="tabs-2">
#using (Ajax.BeginForm("Evaluation","SaveTab2"{new AjaxOptions { Onsucess= "DisplayMessage" }))
{
#Html.HiddenFieldfor(m=>m.fkID)
<input type="Submit" id="btnTab2" value="Submit" />
}
</div>
<div id="tabs-3">
#using (Ajax.BeginForm("Evaluation","SaveTab3"{new AjaxOptions { Onsucess= "DisplayMessage" }))
{
#Html.HiddenFieldfor(m=>m.fkID)
<input type="Submit" id="btnTab3" value="Submit" />
}
</div>
</div>
<script type="text/javascript">
function DisplayMessage(Json)
{
alert( $("#fkID").val(Json.hdn));
// and Alert is showing the value
$("#fkID").val(Json.hdn);
}
</script>
In the Controller I have:
public ActionResult SaveTab1(Model obj)
{
tbl ob =new tbl();
ob.FkId=Obj.fkID;
// after saving, I return
return json(new{hdn=Obj.fkID})
}
public ActionResult SaveTab2(Model obj)
{
tbl ob =new tbl();
ob.FkId=Obj.fkID;
//after saving, I return
return json(new{hdn=Obj.fkID})
}
Similar for tab three, but unfortunately the hidden filed only comes for first form submit. Then I return value to view by json and again set the hidden field property but then it comes null for second form.Please help
First of all, your View does not inherit the Model, it is strongly-typed to the type of your Model. These two are completely different.
But, to answer your question, there's no such a thing as a global hidden field. Fields are not variables. If you want a field to be posted to your Controller, you need to put it inside the form. If you have multiple forms in your View, then you'll have to put the same hidden field inside all the those forms. So, you need to put #Html.HiddenFor(m => m.FkId) inside all the forms in your View.
UPDATE: By the way, it's not Html.HiddenFieldFor, it's Html.HiddenFor.
I have solved the problem. Instead of taking same field in all the forms which was not working, I have taken a unique and different Hidden field properties and after on seperated success function of each form and set the every hidden field a value in success method.

text displaying in every form field

i'm making an Ember app with a Rails back end. In one of the templates, I list the available teams from a database and beside each team put a form field for the user to enter some textual information. If I enter information in one form field, the text appears in all of the form fields (kind of like a multiple cursor experience). That's one problem. Also, when I submit the button to attend one of the conferences, nothing's happening in the controller. I'm wondering if this is a related problem as Ember might think I'm trying to submit from multiple forms at one time due to the fact that these forms are acting as if they're the same form.
Can you see what I'm doing wrong?
<script type="text/x-handlebars" id="conferences">
<div class='span4'>
{{#each item in model}}
<li> {{#link-to 'conference' item}}
{{ item.name }}
{{ partial 'conferences/form'}}
{{/link-to }}</li>
{{/each}}
</ul>
</div>
<div class="span4 offset4">
{{ outlet}}
</div>
</script>
Inserted Form
<script type="text/x-handlebars" id="conferences/_form">
<form class="form-horizontal" {{action "attend" on="submit"}}>
<div class="controls">
{{input value=username type="text"}}
</div>
<button type="submit" class="btn">attend</button>
</form>
</script>
Conferences controller
App.ConferencesController = Ember.ObjectController.extend({
actions: {
attend: function() {
console.log('this is not logging, & no indication rails route is posted to)
$.post("/join_conference_path", {
username: this.get("username"),
}).then(function() {
document.location = "/";
}, function() {
}.bind(this));
}
}
});
Having all input values synced to the same text happen due to fact that each input value is bound to the same property username.
This happens because all _form partials are rendered in the same context which is in your case App.ConferencesController. To make them render in individual context use itemController argument for each helper. See spec here: http://emberjs.com/api/classes/Ember.Handlebars.helpers.html#method_each
{{#each item in model itemController="conference"}}
In this case I suggest you rename your App.ConferencesController to App.ConferenceController which will represent individual context for each "item". Having it done this way your action will always use username input for specific "item" only.
Action may not trigger because by default all actions targets routes and not controllers. Try to add target="controller" attribute to action helper:
{{action "attend" on="submit" target="controller"}}

DropDownListFor not selecting the selected item in the SelectList

I am working on an ASP.NET MVC3 application and I cannot get a DropDownListFor to work with my property in a particular editor view.
My model is a Person and a person has a property that specifies it's "Person Type". PersonType is a class that contains a name/description and an ID. I can access the available PersonTypes within the application through my static/shared class called ApplicationSettings.
In the Edit Template view for my Person I have created a SelectList for debugging purposes:
#ModelType MyNamespace.Person
#Code
Dim pTypesSelectList As New SelectList(MyNamespace.ApplicationSettings.PersonTypes, "ID", "Name", Model.PersonType.ID)
End Code
I am then providing this SelectList as a parameter to the DropDownListFor that is bound to the PersonType property of my Person.
I am also printing the Selected property of each item in the SelectList for debugging purposes:
<div style="text-align: center; margin: 5px 0 0 0;">
<div>
#Html.LabelFor(Function(model) model.PersonType)
</div>
<div>
#Html.DropDownListFor(Function(model) model.PersonType, pTypesSelectList)
#Html.ValidationMessageFor(Function(model) model.PersonType)
<br />
<br />
<!-- The following is debugging code that shows the actual value-->
#Model.Type.Name
<br />
#Model.Type.ID
<br />
<br />
<!--This section is to show that the select list has properly selected the value-->
#For Each pitem In pTypesSelectList
#<div>
#pitem.Text selected: #pitem.Selected
</div>
Next
</div>
</div>
The view is bound to a Person whose PersonType property is "Person Type # 2" and I expect this to be selected; however the HTML output of this code looks like this:
<div style="text-align: center; margin: 5px 0 0 0;">
<div>
<label for="PersonType">PersonType</label>
</div>
<div>
<select id="PersonType" name="PersonType">
<option value="7e750688-7e00-eeee-0000-007e7506887e">Default Person Type</option>
<option value="87e5f686-990e-5151-0151-65fa7506887e">Person Type # 1</option>
<option value="a7b91cb6-2048-4b5b-8b60-a1456ba4134a">Person Type # 2</option>
<option value="8a147405-8725-4b53-b4b8-3541c2391ca9">Person Type # 3</option>
</select>
<span class="field-validation-valid" data-valmsg-for="PersonType" data-valmsg-replace="true"></span>
<br />
<br />
<!-- The following is debugging code that shows the actual value-->
Person Type # 2
<br />
a7b91cb6-2048-4b5b-8b60-a1456ba4134a
<br />
<br />
<!--This section is to show that the select list has properly selected the value-->
<div>
Default Person Type selected: False
</div>
<div>
Person Type # 1 selected: False
</div>
<div>
Person Type # 2 selected: True
</div>
<div>
Person Type # 3 selected: False
</div>
</div>
</div>
As you can see the printed Selected properties for the items in the SelectList shows that the 3rd item is "Selected". But what is driving me crazy is that the option that corresponds with this is Not Selected.
Generally, the Selected property in SelectList will be totally ignored by the HTML helpers unless there's no other option. If DropDownListFor can find the value by other means, it will insist on using that value.
In this case, it will use the value of model.PersonType(.ToString()) - but that's not what you want, judging by the model.PersonType.ID you pass to the SelectList.
More info in the answer here.
Workaround
One easy workaround that should work would be to set:
ViewData["PersonType"] = model.PersonType.Id.
The helper looks in ModelState first if it exists - i.e. on POST. This should work already, since ModelState["PersonType"] will be populated with the actual selected value that was posted.
After ModelState it will look in ViewData - with ViewData["PersonType"] first, and only then ViewData.Model.PersonType. In other words, you can "override" the value on your model with a value set directly on ViewData.
Better (IMO) solution
The more general, "better practice", way to solve it (which also avoids having a custom model binder in order to translate the POST'ed ID back to PersonType) is to use a ViewModel instead of working with full models in your view:
Have a PersonTypeID property - instead of PersonType.
Populate it with PersonType.ID
use this in your view
VB.NET: Html.DropDownListFor(Function(model) model.PersonTypeID), or
C#: Html.DropDownListFor(model => model.PersonTypeID)
When form is POST'ed, translate the ViewModel (including PersonTypeID => PersonType) back into the actual model in your POST Action.
This may seem like more work, but generally there tend to be many occasions in a project where you need more view-specific representations of your data to avoid too much inline Razor code - so translating from business objects to view models, while it may seem redundant and anti-DRY at times, tends to spare you of a lot of headaches.
Are you sure that your ModelState for "PersonType" key before rendering the view is empty? As JimmiTh commented is going to search for the value in the ModelState first. It happened to me too, you can try
#Html.DropDownList("PersonTypeFake", Function(model) model.PersonType, pTypesSelectList) and it should select the right option.

Resources