Use Devextreme js Widget in ASP.NET Core - asp.net-mvc

I'm trying to find a way to use Devextreme RadioGroup js widget with ASP.NET Core.
I've created this simple View:
<form asp-action="SelectSourceData" asp-controller="Home" method="post">
<div class="form-group">
<label for="rg-mode">Please Choose Migration Mode</label>
<div id="rg-mode"></div>
</div>
<button type="submit" class="btn btn-primary">Proceed</button>
</form>
#section Scripts {
<script>
$(function () {
$("#rg-mode").dxRadioGroup({
dataSource: modes,
displayExpr: "text",
valueExpr: "val",
value: "by-org"
})
});
var modes = [
{ text: "By Organisation", val: "by-org" },
{ text: "By Contract Type", val: "by-contr" },
{ text: "By Employee", val: "by-emp" },
{ text: "Mixed Mode", val: "mm" }
];
</script>
}
When user presses Proceed button SelectSourceData action method is invoked:
[HttpPost]
public ViewResult SelectSourceData(string val)
{
// get selected value here ... ?
return View();
}
My question is: is it possible to somehow obtain the value selected in dxRadioGroup widget?

Following #Stephen's advice I added a hidden input field:
<div class="form-group">
<input id="hdnMode" name="mode" type="hidden" value="by-org" class="form-control" />
<label for="rg-mode">Please Choose Migration Mode</label>
<div id="rg-mode"></div>
</div>
and registered a handling function for value changed event:
$(function () {
$("#rg-mode").dxRadioGroup({
dataSource: modes,
displayExpr: "text",
valueExpr: "val",
value: "by-org",
onValueChanged: function (e) {
var previousValue = e.previousValue;
var newValue = e.value;
// Event handling commands go here
$("#hdnMode").val(newValue);
}
})
});
The action method now correctly obtains the value submitted by the form:
[HttpPost]
public ViewResult SelectSourceData(string mode)
{
// mode argument successfully set to submitted value
var t = mode;
....

Related

Submitting Form once but automatically being doubled / twice on POST method? ASP.NET MVC

I am currently working on a project in asp.net(v4.6) mvc(v5), it was working properly on first deployment on the remote server, after the first test trial its giving errors on forms when i submit on POST method.
It is automatically posting the form twice which is not required.
Places i checked for errors:
source code (also DEBUG)
searched and tried Logs
used tools to check why and from where this issue is occurring (no results)
I fix i found was the browser issue, when i changed from chrome to edge there was no errors... But there is still no notes on what the error is and how it is being generated.
Here is the View.cshtml
#using (Html.BeginForm("Create", "AdmissionCell", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="col-md-12">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#*Input Fields Here*#
<div class="form-group">
<div class="col-md-offset-4 col-md-6">
<input type="submit" value="Save Student Record" class="btn btn-primary btn-lg" />
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script>
$(document).ready(function () {
$("#CNIC").change(function () {
$.get("/AdmissionCell/CheckCNIC",
{ cnic: $("#CNIC").val() },
function (data) {
if (data === 1) {
//alert("Sorry, CNIC already exists, Please enter unique CNIC. or ");
//location.reload();
var cnicStu = $("#CNIC").val();
if (window.confirm('Sorry, CNIC already exists, Please enter unique CNIC or Press "Ok" to goto student details.')) {
window.location.href = "/AdmissionCell/Details?cnic=" + cnicStu;
};
}
});
});
});
</script>
<script>
$(function () {
$('.cnic').on('keyup', function () {
var input = $('.cnic').val();
if (input.length == 5 || input.length == 13) {
$('.cnic').val(input + '-');
}
});
$('.gcnic').on('keyup', function () {
var input = $('.gcnic').val();
if (input.length == 5 || input.length == 13) {
$('.gcnic').val(input + '-');
}
});
});
</script>
}
I suspect your jqueryval bundle is included twice.
Once in the view (as shown) and also in your _layout file, so the events are bound twice

Dynamically add multiple fields to be validated using bootstrap validator

I have gone through the example here. But it illustrates dynamic addition of a single input field. I have to add multiple dynamic input fields. How can I achieve it? Refer this example jsfiddle
I need to dynamically add all the three fields in the table row on clicking button through.
You can try somethings like this:
<form id="myForm" action="myAction">
<div class="row" id="line_1">
<div class="col-md-2 form-group">
<input type="text" class="form-control input-sm" id="idFirstField_1" name="firstField[]">
</div>
<div class="col-md-2 form-group">
<input type="text" class="form-control input-sm" id="idSecondField_1" name="secondField[]">
</div>
<div class="col-md-2 form-group">
<input type="text" class="form-control input-sm" id="idThirdField_1" name="thirdField[]">
</div>
</div>
<a id="cloneButton">add line</a>
</form>
In the JavaScript file you must to use the function clone() and to change the id of each input if you want:
$(document).ready(function () {
var count = 2;
$('#cloneButton').click(function () {
var klon = $('#line_1');
klon.clone().attr('id', 'line_' + (++count)).insertAfter($('#line_1'));
$('#line_' + count).children('div').children('input').each(function () {
$(this).val('');
var oldId = $(this).attr('id').split('_');
$(this).attr('id', oldId[0] + '_' + count);
});
});
//if you want to validate the fields, then you can use this code:
$('#myForm').bootstrapValidator({
fields: {
'firstField[]': {
validators: {
notEmpty: {
message: 'Enter a value'
}
}
},
'secondField[]': {
validators: {
notEmpty: {
message: 'Enter a value'
}
}
},
'thirdField[]': {
validators: {
notEmpty: {
message: 'Enter a value'
}
}
}
}
});
});
Now the bootstrap validation does not will work for cloned fields because you must to use in the JavaScript file somethings like this
$('#myForm').bootstrapValidator('addField', $option); //(from your link http://bootstrapvalidator.com/examples/adding-dynamic-field/ )
but who will contains all fields. I don't now how to do it.

bind kendo.data.DataSource to combo using MVVM

Again next question , this time a tricky one,
Datasource:
var dsCountryList =
new kendo.data.DataSource({
transport: {
read: {
dataType: "jsonp",
url: "/Masters/GetCountries"
}
},
schema: {
model: {
id: "CountryID",
fields: {
"CountryDesc": {
}
}
}
}
});
Observable object
function Set_MVVMSupplier() {
vmSupplier = kendo.observable({
SupplierID: 0,
SupplierName: "",
AccountNo: "",
CountryList: dsCountryList,
});
kendo.bind($("#supplierForm"), vmSupplier);
}
here is the html which is bind to observable object , but i am not getting combobox filled, also each time i clicked the combo request goes to server and bring data in json format for countryID, CountryDesc
<div class="span6">
<div class="control-group">
<label class="control-label" for="txtCountryId">Country</label>
<div class="row-fluid controls">
#*<input class="input-large" type="text" id="txtCountryId" placeholder="CountryId" data-bind="value: CountryId">*#
<select id="txtCountryId" data-role="dropdownlist"
data-text-field="CountryDesc" data-value-field="CountryID" , data-skip="true"
data-bind="source: CountryList, value: CountryDesc">
</select>
</div>
</div>
</div>
I didn't get the answer , so i found an alternate working ice of code. just have a look and if it helps then please vote.
created model for ddl in js file
ddl = kendo.data.Model.define({
fields: {
CountryId: { type: "int" },
ConfigurationID: { type: "int" }
}
});
added var ddl to MVVM js file
vmSupplier = kendo.observable({
CountryId: new ddl({ CountryId: 0 }),
ConfigurationID: new ddl({ ConfigurationID: 0 }),});
added code in controller
using (CountriesManager objCountriesManager = new CountriesManager())
{
ViewBag.Countries = new SelectList(
objCountriesManager.GetCountries().Select(p => new { p.CountryID, p.CountryDesc })
, "CountryID", "CountryDesc"); ;
}
added code in cshtml
<div class="span4">
<label class="control-label" for="txtCountryId">Country</label>
#Html.DropDownList("Countries", null,
new System.Collections.Generic.Dictionary<string, object> {
{"id", "txtCountryId" },
{ "data-bind","value: CountryId"} })
</div>
this way i got solved the problem

pass model from view to controller with html.actionlink

I am trying to get the model data from a strongly typed view to a controller.
Using the submit button is ok, I can get the data. Now I want to achieve the same with html.actionlink.
This is what I have:
View:
#model WordAutomation.Models.Document
#{
ViewBag.Title = "Document";
}
<script type="text/javascript">
$(function () {
$("#dialog").dialog();
});
</script>
<h2>Document</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Document</legend>
<div class="editor-label">
#Html.LabelFor(model => model.ClientTitle)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ClientTitle)
#Html.ValidationMessageFor(model => model.ClientTitle)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ClientFullName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ClientFullName)
#Html.ValidationMessageFor(model => model.ClientFullName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ClientCustomSSN)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ClientCustomSSN)
#Html.ValidationMessageFor(model => model.ClientCustomSSN)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Preview", "PreviewWordDocument", "Home", null, new { id = "previewLink" })
</div>
<div id="dialogcontainer">
<div id="dialogcontent"><input type="submit" value="Create" /> </div>
</div>
#section Scripts {
<script type="text/javascript">
$(document).ready(function() {
$("#dialogcontainer").dialog({
width: 400,
autoOpen:false,
resizable: false,
title: 'Test dialog',
open: function (event, ui) {
$("#dialogcontent").load("#Url.Action("PreviewWordDocument", "Home")");
},
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
$("#previewLink").click(function(e) {
e.preventDefault();
$("#dialogcontainer").dialog('open');
});
});
</script>
}
Controller:
public ActionResult Document()
{
return View();
}
[HttpPost]
public ActionResult Document(WordAutomation.Models.Document model)
{
Models.Utility.EditWord word = new Models.Utility.EditWord();
word.EditWordDoc(model);
return View("Display", model);
}
public ActionResult PreviewWordDocument()
{
var image = Url.Content("~/Content/preview.jpeg");
return PartialView((object)image);
}
The document actionresult can get the model, but I want to know how can I get the values from the actionlink which will trigger the PreviewWordDocument action.
Thanks in advance, Laziale
The form can only be posted using the submit button to the URL given by its action attribute.
You can however send the form data to a different URL using the jQuery post method, manually validating the form before it is sent.
That way you can send the form data to the PreviewWordDocument controller method and handle the response in order to show the preview in the desired div.
(It will be helpful if you give an id to the form, so you can easily find it using jQuery)
So your click event handler for the preview link will look like this:
$("#previewLink").click(function(e) {
e.preventDefault();
if($("#YourFormId").valid()){
$("#dialogcontainer").dialog('open');
}
});
In the open function of the dialog you will post the form (which was already validated) to the preview controller method, using the jQuery ajax function. The response will be loaded into the dialogContent div:
$.ajax({
type: "POST",
url: $("#previewLink").attr("href"), //the preview controller method
data: $("#YourFormId").serialize(),
success: function (data) {
//load ajax response into the dialogContent div
$("#dialogcontent").html(data);
},
error: function(xhr, error) {
$("#YourFormId").prepend('<div id="ajaxErrors"></div>')
.html(xhr.responseText);
}
});
Now you will now be able to receive the whole document in the PreviewWordDocument action:
public ActionResult PreviewWordDocument(WordAutomation.Models.Document model)
{
var image = Url.Content("~/Content/preview.jpeg");
return PartialView((object)image);
}
in a HTML page when you click on a submit button all the input elements inside the form which the submit button resides in will posted to server, but when you click on a anchor (<a> tag ). you only send a request with a Get method and without posting any value.but if you want to send particular value to the server with this approach you can do it by query string.you have used following to make a request :
#Html.ActionLink("Preview", "PreviewWordDocument", "Home", null,
new { id = "previewLink" })
this will produce :
<a id="previewLink" href="/Home/PreviewWordDocument"> Preview </a>
which is incorrect.to pass any value to the server with ActionLink use 4th parameter like this :
#Html.ActionLink("Preview", "PreviewWordDocument", "Home",
new { id = "previewLink" }, null)
the result from this code would be :
Preview
cheers!

knockoutjs template jquery autocomplete - how to populate inputs on autocomplete select?

I want to populate multiple inputs inside a template after select of an autocomplete item. I'm following http://jsfiddle.net/rniemeyer/MJQ6g/ but not sure how to apply this to multiple inputs.
Model:
<script>
var ContactModel = function (contactsInfo) {
var self = this;
self.Company = ko.observable();
self.ContactsInformation = contactsInfo;
self.Name = ko.observable();
};
var ContactsInformationModel = function () {
var self = this;
self.Address1 = ko.observable();
};
var viewModel;
var ViewModel = function () {
var self = this;
self.Contact1 = new ContactModel(new ContactsInformation);
self.Contact2 = new ContactModel(new ContactsInformation);
};
$(function () {
viewModel = new ViewModel();
ko.applyBindings(viewModel);
});
function getContacts(searchTerm, sourceArray) {
$.getJSON("web_service_uri" + searchTerm, function (data) {
var mapped = $.map(data, function (item) {
return {
label: item.Name,
value: item
};
});
return sourceArray(mapped);
});
}
</script>
Template:
<script type="text/html" id="contact-template">
<div>
Name
<input data-bind="uniqueName: true,
jqAuto: { autoFocus: true, html: true },
jqAutoSource: $root.Contacts,
jqAutoQuery: getContacts,
jqAutoValue: Name,
jqAutoSourceLabel: 'label',
jqAutoSourceInputValue: 'value',
jqAutoSourceValue: 'label'"
class="name" />
</div>
<div>
Company
<input data-bind="value: Company, uniqueName: true" class="company" />
</div>
<div>
Address
<input data-bind="value: ContactsInformation.Address1, uniqueName: true" class="address1" />
</div>
</script>
Html:
<div data-bind="template: { name: 'contact-template', data: Contact1 }">
</div>
<hr/>
<div data-bind="template: { name: 'contact-template', data: Contact2 }">
</div>
If you leave out the jqAutoSourceValue option from your data-bind, then it will set the value equal to the actual object. Then, you can read properties off of that object.
Usually, you would have an observable like: mySelectedPerson and then bind a section (possibly with the with binding) against it and access the individual properties/observables off of that object.
Here is the sample modified to leave out the jqAutoSourceValue option, bind jqAutoValue against an observable called mySelectedPerson and use the with binding to display some properties from the selected object. http://jsfiddle.net/rniemeyer/YHvyL/

Resources