Fill DropDownList Value from Database using Knockout - c#

I'm using jQuery Ajax to load the data from the server and then bind it using Knockout JS, but the values do not display in DropDownList.
Here is the code:
View: Edit.cshtml
...
<div class="tab-content">
...
<div class="tab-pane" id="pnlLiquidation">
#{ Html.RenderPartial("~/Views/Liquidation/_Liquidation.cshtml", Model.LiquidationVM); }
</div>
</div>
...
#section Scripts {
#Scripts.Render("~/bundles/jqueryui")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/knockout")
<script>
...
var companyID = #Html.Raw(ViewBag.CompanyID);
...
</script>
...
<script src="~/Scripts/LiquidationSystem/account-statement.js"></script>
...
}
View: _Liquidation.cshtml
...
<div class="tab-content">
...
<div class="tab-pane" id="pnlStage2Steps28_29">
#{ Html.RenderPartial("~/Views/Liquidation/_Stage2Steps28_29.cshtml", Model); }
</div>
...
</div>
View: _Stage2Steps28_29.cshtml
...
<div class="panel panel-primary">
<div class="panel-body" id="pnlAccountStatement">
#{ Html.RenderPartial("~/Views/AccountStatement/_AccountStatement.cshtml"); }
</div>
</div>
...
View: _AccountStatement.cshtml
<div class="row">
<div class="col-md-12">
Add New Statement of Accounts
<div class="form-horizontal" id="pnlAddEditAccountStatement">
<div data-bind="if: AccountStatement">
<h4>Update Statement of Account</h4>
...
</div>
<div data-bind="ifnot: AccountStatement()">
<h4>Add New Statement of Account</h4>
<div class="form-group">
<label class="control-label col-md-2">Type:</label>
<div class="col-md-10">
<select class="form-control"
data-bind="options: Types, optionsValue: 'Value', optionsText: 'Text', optionsCaption: '-- Please Select --', value: Type"></select>
</div>
</div>
<div class="form-group">
<input type="hidden" data-bind="value: $root.CompanyID" />
<label class="control-label col-md-2">Description:</label>
<div class="col-md-10">
<input type="text" placeholder="Enter Description" class="form-control"
data-bind="value: $root.Description" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">Amount:</label>
<div class="col-md-4">
<input type="text" placeholder="Enter Amount" class="form-control"
data-bind="value: $root.Amount" />
</div>
<label class="control-label col-md-2">Receipt Date:</label>
<div class="col-md-4">
<input type="text" placeholder="Enter Receipt Date" class="form-control fdatepicker" readonly="readonly"
data-bind="value: $root.ReceiptDate" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
Save
Reset
Cancel
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<h4>
<i>
<u>List of Statement of Accounts</u>
</i>
</h4>
...
</div>
</div>
Javascript: account-statement.js
function AccountStatementViewModel(companyID) {
var self = this;
self.AccountStatementID = ko.observable();
self.CompanyID = ko.observable(companyID);
self.Description = ko.observable();
self.Amount = ko.observable();
self.ReceiptDate = ko.observable();
self.Type = ko.observable();
var AccountStatement = {
AccountStatementID: self.AccountStatementID,
CompanyID: self.CompanyID,
Description: self.Description,
Amount: self.Amount,
ReceiptDate: self.ReceiptDate,
Type: self.Type
}
self.AccountStatement = ko.observable();
self.AccountStatements = ko.observableArray();
$.ajax({
url: webroot + 'AccountStatement/GetAccountStatements',
contentType: 'application/json; charset=utf-8',
data: { id: self.CompanyID },
cache: false
}).done(function (data) {
self.AccountStatements(data);
});
var clearInput = function () { ... }
self.create = function () { ... }
self.reset = function () { ... }
self.edit = function (accountStatement) { ... }
self.update = function () { ... }
self.cancel = function () { ... }
self.delete = function (accountStatement) { ... }
}
var accountStatementVM = new AccountStatementViewModel(companyID);
ko.applyBindings(accountStatementVM, document.getElementById('pnlAccountStatement'));
var Types;
$(function () {
$('#pnlAddEditAccountStatement').hide();
$('#lnkAddAccountStatement').click(function (e) {
e.preventDefault();
$('#pnlAddEditAccountStatement').show('blind', 1000);
$(this).hide('blind', 1000);
});
$.ajax({
url: webroot + 'AccountStatement/GetTypes',
contentType: 'application/json; charset=utf-8',
async: false,
cache: false,
dataType: 'json'
}).done(function (data) {
console.log('data = ' + data);
Types = data;
console.log('Types[0].Text = ' + Types[0].Type);
console.log('Types[0].Value = ' + Types[0].Description);
console.log('Types[1].Text = ' + Types[1].Type);
console.log('Types[1].Value = ' + Types[1].Description);
});
});
When I see the console:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
data = [object Object],[object Object]
account-statement.js:151 Types[0].Text = Receipts
account-statement.js:152 Types[0].Value = Receipts
account-statement.js:153 Types[1].Text = Payment
account-statement.js:154 Types[1].Value = Payment
Controller: AccountStatementController.cs
public JsonResult GetTypes()
{
List<SelectListItem> types = new List<SelectListItem>
{
new SelectListItem
{
Text = "Receipts",
Value = "Receipts"
},
new SelectListItem
{
Text = "Payment",
Value = "Payment"
}
};
}
Can I use SelectListItem rather than create the View Model? I've tried to create AccountStatementTypeViewModel.cs and replace the SelectListItem.
AccountStatementTypeViewModel.cs
public class AccountStatementTypeViewModel
{
public string Type { get; set; }
public string Description { get; set; }
}
update the GetTypes() method
public JsonResult GetTypes()
{
List<AccountStatementTypeViewModel> types = new List<AccountStatementTypeViewModel>
{
new AccountStatementTypeViewModel
{
Type = "Receipts",
Description = "Receipts"
},
new AccountStatementTypeViewModel
{
Type = "Payment",
Description = "Payment"
}
};
return Json(types, JsonRequestBehavior.AllowGet);
}
update the select tag in _AccountStatement.cshtml
<select class="form-control"
data-bind="options: Types, optionsValue: 'Type', optionsText: 'Description', value: Type"></select>
but the result is same, it cannot bind into the DropDownList value.
I've followed the code from this site and download the source code and see the code how do they fill the Phone Type dropdownlist. The tutorial use ASP.NET MVC 4, jQuery 1.8.3, and Knockout 2.2.0, but mine using ASP.NET MVC 5, jQuery 2.1.4, and Knockout 3.3.0. Is there any problem with the version differences?

Related

How to Get time using AngularJs then bind it to input time from view to controller

I am working on a project that uses ASP.NET MVC and AngularJS, i am
trying to use time input type to set and get time from database i am
using code first approach , my question is i want to get the time from
database then bind it to input time, i inserted the time successfully
to the database but i have problem i can not bind it with the input
time control.
**Model**
public class Branches
{
public int Branch_ID { get; set; }
public string Branch_Name { get; set; }
public string Branch_Address { get; set; }
public string Branch_email { get; set; }
public string Branch_Notes { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = #"{0:hh\:mm}")]
public TimeSpan Branch_TimeFrom { get; set; }
[DataType(DataType.Time)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = #"{0:hh\:mm}")]
public TimeSpan Branch_TimeTo { get; set; }
}
**Controller**
public class BranchesController : Controller
{
private IRepositoryBase<Branches> BrancheRepository;
public BranchesController()
{
this.BrancheRepository = new BranchesRepository(new HrmDBContext());
}
public BranchesController(IRepositoryBase<Branches> brancheRepository)
{
this.BrancheRepository = brancheRepository;
}
// GET: Branches
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Create(Branches branch)
{
try
{
if (ModelState.IsValid)
{
BrancheRepository.Create(branch);
//var branches = BrancheRepository.GetAll();
//return Json(new
//{
// d = true,
// pv = RazorToString(this, "~/views/Branches/list.cshtml", branches),
//}, JsonRequestBehavior.AllowGet);
return Json(new { success = true });
}
else
{
return Json(new { success = false });
}
}
catch (DataException dex)
{
ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem
persists contact your system administrator.");
return Json(new { success = false });
}
// return View(branch);
}
[HttpPost]
public JsonResult Edit(Branches branch)
{
try
{
if (ModelState.IsValid)
{
BrancheRepository.Update(branch);
return Json(new { success = true });
}
else
{
return Json(new { success = false });
}
}
catch (DataException dex )
{
//Log the error (uncomment dex variable name after DataException and add a line here to write a log.
ModelState.AddModelError(string.Empty, "Unable to save changes. Try again, and if the problem persists contact your system administrator.");
return Json(new { success = false });
}
}
}
**FetchBranchData.js**
var app = angular.module('myapp', []);
app.service("myService", function ($http) {
//get All Branches
this.getAllBranches = function () {
return $http.get("Branches/GetAllBranches");
};
//$http.get(url).then(response) {
// var data = response.data;
// data.Branch_TimeFrom = new Date(data.Branch_TimeFrom);
// data.Branch_TimeTo = new Date(data.Branch_TimeTo);
// $scope.data = data;
//});
//add new Branch
this.save = function (Branch) {
var request = $http({
method: 'post',
url: '/Branches/Create',
data: Branch
});
return request;
};
//update Employee records
this.update = function (Branch) {
var updaterequest = $http({
method: 'post',
url: '/Branches/Edit',
data: Branch
});
return updaterequest;
};
});
app.controller("branchcontroller", function ($scope, myService) {
getAllBranches();
function getAllBranches() {
var getData = myService.getAllBranches();
getData.then(function (response) {
$scope.Branches = response.data;
}, function (error) {
console.log(error);
alert('Error in getting records');
});
};
//save Branch data
$scope.save = function () {
debugger
var Branch = {
Branch_Name: $scope.Branch_Name,
Branch_Address: $scope.Branch_Address,
Branch_email: $scope.Branch_email,
Branch_Notes: $scope.Branch_Notes,
Branch_TimeFrom: moment($scope.Branch_TimeFrom).format('HH:mm:ss'),
Branch_TimeTo: moment($scope.Branch_TimeTo).format('HH:mm:ss'),
Branch_Manager: $scope.Branch_Manager,
Branch_Phone: $scope.Branch_Phone,
saturday: $scope.saturday
};
var saverecords = myService.save(Branch);
saverecords.then(function (response) {
if (response.data.success === true) {
getAllBranches();
alert("Branch added successfully");
$scope.resetSave();
}
else { alert("Branch not added."); }
},
function () {
alert("Error occurred while adding branch.");
});
};
//reset controls after save operation
$scope.resetSave = function () {
$scope.Branch_Name = '';
$scope.Branch_Address = '';
$scope.Branch_email = '';
$scope.Branch_Notes = '';
$scope.Branch_TimeFrom = '';
$scope.Branch_TimeTo = '';
$scope.Branch_Manager = '';
$scope.Branch_Phone = '';
$scope.saturday = '';
};
//get single record by ID
$scope.getForUpdate = function (Branch) {
debugger
$scope.Branch_ID = Branch.Branch_ID;
$scope.Branch_Name = Branch.Branch_Name;
$scope.Branch_Address = Branch.Branch_Address;
$scope.Branch_email = Branch.Branch_email;
$scope.Branch_Notes = Branch.Branch_Notes;
$scope.Branch_TimeFrom = moment(Branch.Branch_TimeFrom).format('hh:mm:ss a');
$scope.Branch_TimeTo = moment(Branch.Branch_TimeTo).format('hh:mm:ss a');
$scope.Branch_Manager = Branch.Branch_Manager;
$scope.Branch_Phone = Branch.Branch_Phone;
$scope.saturday = Branch.saturday;
};
//update Branch data
$scope.update = function () {
var Branch = {
Branch_ID: $scope.Branch_ID,
Branch_Name: $scope.Branch_Name,
Branch_Address: $scope.Branch_Address,
Branch_email: $scope.Branch_email,
Branch_Notes: $scope.Branch_Notes,
Branch_TimeFrom: $scope.Branch_TimeFrom,
Branch_TimeTo: $scope.Branch_TimeTo,
Branch_Manager: $scope.Branch_Manager,
Branch_Phone: $scope.Branch_Phone,
saturday : $scope.saturday
};
var updaterecords = myService.update(Branch);
updaterecords.then(function (response) {
if (response.data.success === true) {
getAllBranches();
alert("Branch updated successfully");
$scope.resetUpdate();
}
else {
alert("Branch not updated.");
}
},
function () {
alert("Error occured while updating Branch record");
});
};
//reset controls after update
$scope.resetUpdate = function () {
$scope.Branch_Name = '';
$scope.Branch_Address = '';
$scope.Branch_email = '';
$scope.Branch_Notes = '';
$scope.Branch_TimeFrom = '';
$scope.Branch_TimeTo = '';
$scope.Branch_Manager = '';
$scope.Branch_Phone = '';
$scope.saturday = '';
};
};
Index.cshtml
<div class="container" ng-controller="branchcontroller">
<table class="table table-bordered">
<thead style="background-color:lightblue;">
<tr>
<th>Branch Address</th>
<th>Branch Email</th>
<th>Branch Name</th>
<th>Branch Notes</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="branche in Branches">
<td>{{branche.Branch_Address}}</td>
<td>{{branche.Branch_email}}</td>
<td>{{branche.Branch_Name}}</td>
<td>{{branche.Branch_Notes}}</td>
<td style="width:200px;">
<a href="#"
class="btn btn-info"
data-toggle="modal"
data-target="#Update"
ng-click="getForUpdate(branche)">
Update
</a>
<a href="#" class="btn btn-danger"
id="btnDelete"
data-toggle="modal"
data-target="#deleteDialog"
ng-click="getForDelete(branche)">
Delete
</a>
</td>
</tr>
</tbody>
</table>
#*Upadate Branch records*#
<div class="modal" id="Update" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="text-info">Update Existing Branch</h3>
</div>
<div class="modal-body" style="margin-left:20px">
#*Update Employee form starts here...*#
<form class="form-horizontal" name="UpdateBranchForm">
<div class="form-group">
<input class="form-control" readonly="readonly" name="Branch_ID" ng-model="Branch_ID" type="hidden" placeholder="Branch ID" />
</div>
<div class="form-group">
<label class="control-label"> Branch Address</label>
<input class="form-control" name="Branch_Address" ng-model="Branch_Address" type="text" placeholder="Branch Address" />
</div>
<div class="form-group">
<label class="control-label"> Branch email</label>
<input class="form-control" name="Branch_email" ng-model="Branch_email" type="email" placeholder="Branch email" />
</div>
<div class="form-group">
<label class="control-label"> Branch Name</label>
<input class="form-control" name="Branch_Name" ng-model="Branch_Name" type="text" placeholder="Branch Name" />
</div>
<div class="form-group">
<label class="control-label"> Branch Manager</label>
<input class="form-control" name="Branch_Name" ng-model="Branch_Manager" type="text" placeholder=" Branch Manager" />
</div>
<div class="form-group">
<label class="control-label"> Branch Phone</label>
<input class="form-control" name="Branch_Name" ng-model="Branch_Phone" type="text" placeholder="Branch Phone" />
</div>
<div class="form-group">
<label class="control-label"> Branch Notes</label>
<textarea class="form-control" name="Branch_Notes" ng-model="Branch_Notes" placeholder="Branch Notes"></textarea>
</div>
<div class="form-group">
<label class="control-label"> Time From</label>
<input ng-model="Branch_TimeFrom" type="time" name="Branch_TimeFrom" placeholder="HH:mm">
</div>
<div class="form-group">
<label class="control-label"> Time To</label>
<input ng-model="Branch_TimeTo" type="time" name="Branch_TimeTo" placeholder="HH:mm">
</div>
<div class="form-group">
<label class="control-label"> saturday</label>
<input ng-model="saturday" type="checkbox" name="saturday" placeholder="saturday">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btnUpdate" data-dismiss="modal" ng-click="update()">
Update
</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
here i want to get time from database then display it in input type
time
here is the time that i get it from database then i want it to
display to input type time
The AngularJS framework needs to bind JavaScript Date objects:
$http.get(url).then(response) {
var data = response.data;
data.Branch_TimeFrom = new Date(data.Branch_TimeFrom);
data.Branch_TimeTo = new Date(data.Branch_TimeTo);
$scope.data = data;
});
<label class="control-label"> Branch Notes</label>
<textarea ng-model="data.Branch_Notes">
</textarea>
<label class="control-label"> Time From</label>
<input ng-model="data.Branch_TimeFrom" type="time">
<label class="control-label"> Time To</label>
<input ng-model="data.Branch_TimeTo" type="time">
From the Docs:
The model must always be a Date object, otherwise AngularJS will throw an error. Invalid Date objects (dates whose getTime() is NaN) will be rendered as an empty string.
For more information, see
AngularJS <input type="time"> Directive API Reference

view in mvc can not render html for the second time

when I try to render HTML in view for the second time the HTML not change and nothing happens it still as it aims calling the same view two times when the modal is empty and when I fill modal with data and then try to render it
this is the view
<section class="col-12 m-b-60">
<h2 class="m-b-20">Deduction</h2>
<form class="form-inline">
<div class="row">
<div class="col-6">
<div class="input-group">
<label class="input-text">
<span class="label">Employee ID</span>
<input type="text" placeholder="Employee ID ..."id="employeid">
</label>
<a class="btn btn-default" onclick="veiwemployee()">
Get
</a>
</div>
</div>
<div class="col-6">
<div class="input-group">
</div>
</div>
</div>
</form>
</section>
<section class="col-12 m-b-20">
`#if (Model != null)`
{
#await Html.PartialAsync("/Views/Home/View.cshtml", Model);
}
</section>
The action
public IActionResult EmployeeDeduction(int employeeID = 0)
{
Deduction deduction = new Deduction() ;
if (employeeID == 0) { }
else
{
ModelState.Clear();
deduction = _conn.GetEmployeByEmployeeID(employeeID);
}
return View("/Views/view.cshtml",deduction);
}
The Js function
function veiwemployee() {
if ($("#employeid").val() == "") {
$("#employeid").style.borderColor = "red";
}
else {
$.ajax({
type: 'POST',
url: '/Home/EmployeeDeduction?employeeID=' + $("#employeid").val(),
async: false,
dataType: 'json',
success: function (resp) {
}
});
}
}
this tag does not have closing.
<input type="text" placeholder="Employee ID ..." id="employeid">
"/" missing

How to call user control method using jQuery AJAX in Asp.Net

Here is the acsx page.
I have two drop down in Bootstrap modal (State and City).
Based on the state selection, City dropdown should populate option.
I have created two methods in code behind for state FillStatedata() and for city getCitydata().
I need to call getCitydata() method on state selection change using jQuery AJAX and then bind the city data with city drop down.
I am getting Statename on state change but not able to executive getCitydata() method using statename as parameter.
Why?
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="Registeration.ascx.cs" Inherits="WebApplication1.UserControl.Registeration" %>
<%# Import Namespace = "System.Web.Security" %>
<script src="~/scripts/jquery-1.10.2.js"></script>
<script src="~/scripts/jquery-1.10.2.min.js"></script>
<!--jquery start here-->
<script>
$(document).ready(function () {
var getSelState;
$("#State").change(function () {
$.ajax({
type: "POST", //HTTP method
url: "UserControl/Registeration.ascx/getCitydata", //page/method name
data: alert("{'Statename':'" + $('#State').val() + "'}"), //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) { //handle the callback to handle response
//request was successful. so Retrieve the values in the response.
}
})
});
});
</script>
<input type="hidden" id="myhiddenField" name="myhiddenField" value="" ClientIDMode="Static" runat="server" />
<div class="form-horizontal" role="form" runat="server">
New User?
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Register</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="full-name" class="col-sm-2 control-label">FullName:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="full-name">
</div>
</div>
<div class="form-group">
<label for="User-Name" class="col-sm-2 control-label">Username:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="User-Name">
</div>
</div>
<div class="form-group">
<label for="Create-Password" class="col-sm-2 control-label">Create Password:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Create-Password">
</div>
</div>
<div class="form-group">
<label for="confirm-Password" class="col-sm-2 control-label">Confirm Password:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Confirm-Password">
</div>
</div>
<div class="form-group">
<label for="Mobile-Number" class="col-sm-2 control-label">Mobile No:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="Mobile-Number">
</div>
</div>
<div class="form-group">
<label for="State" class="col-sm-2 control-label">State:</label>
<div class="col-sm-10">
<select class="form-control" id="State" runat="server" ClientIDMode="Static">
</select>
</div>
</div>
<div class="form-group">
<label for="City" class="col-sm-2 control-label">City:</label>
<div class="col-lg-10">
<select class="form-control" id="City" runat="server" DataTextField="Cityname"
DataValueField="Cityname"></select>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<button type="button" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-primary">Cancel</button>
</div>
</div>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
First things first.
just use one library either min for prod or non min for dev.
data:{} should have to be an object or string value.
use one of it:
<script src="~/scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function() {
var getSelState;
$("#State").change(function() {
$.ajax({
type: "POST", //HTTP method
url: "UserControl/Registeration.ascx/getCitydata", //page/method name
data: "{'Statename':'" + this.value + "'}", //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function(msg) { //handle the callback to handle response
console.log(msg);
}
});
});
});
</script>
function getCitydata()(obj) {
var ddlcity = document.getElementById('<%= ddlcity.ClientID %>');
ddlcity.innerHTML = '';
$.support.cors = true;
var serviceUrl = '/ashx/map/Address.ashx';
if (serviceUrl.indexOf('?') > -1)
serviceUrl += '&jsonp='
else
serviceUrl += '?jsonp='
serviceUrl += '?&type=1&StateId=';
serviceUrl += document.getElementById('<%= ddlState.ClientID%>').value;
$.ajax({
type: 'GET',
crossDomain: true,
async: false,
contentType: 'application/json; charset = utf-8',
url: serviceUrl,
data: '{}',
dataType: 'jsonp',
success: function (data) {
if (data != null && data.length > 0) {
$.map(data, function (item, index) {
var newListItem = document.createElement('option');
newListItem.text = item.City;
newListItem.value = item.CityId;
ddlcity.options.add(newListItem);
});
}
},
error: function (error) {
alert('error ' + error);
}
});
} // getCitydata()
To use this function you have to create one ashx file eg. Address.ashx file which consist method for getting the data from database

Can't see my Controller object in my MVC 5 View

I'm new to MVC, and I'm writing my first App in this technology.
i'm trying to return an Object to my view from the controller, but I can't see it in the view, hear is my Controller code:
`
public ActionResult Create(int id)
{
AddAffiliatModel serverUsersModel = new AddAffiliatModel();
ObjectResult<getServerUsers_Result> serverUsers = serverUsersModel.getSUsers();
List<getServerUsers_Result> users = serverUsers.ToList();
return View(users[0]);
}`
And here is my View code:
#model MVC_5_Skeleton1.Models.getServerUsers_Result
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>getUsers</title>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<script src="~/JS/AddAffiliate.js"></script>
<style>
.txtW {
max-width: 300px;
}
.txtAH {
height: 200PX;
}
</style>
<script type="text/javascript">
//**************************************************************************
//** Jquery Ready function hooks the buttons click events *
//**************************************************************************
$(document).ready(function () {
$(document).on('click', 'button', function (e) {
buttonId = $(this).attr("id");
switch (buttonId) {
case "submit":
Validate();
clearFields();
break;
case "cancel":
break;
default:
break;
}
});
});
//**************************************************************************
//** Validate and send *
//**************************************************************************
function SendToServer() {
}
//**************************************************************************
//** Validate and send *
//**************************************************************************
function Validate() {
var errorMsg = "";
var postString = "";
var valid = 0;
var filter = /^([a-zA-Z0-9_\.\-])+\##(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if ($('#fullName').val().length > 2) {
var name = $('#fullName').val();
}
else {
errorMsg = 'Please enter name';
valid = 1;
}
if ($('#email').val().length > 5) {
var email = $('#email').val();
}
else {
errorMsg += 'Please valid email' + '/n';
valid = 1;
}
if ($('#skype').val().length > 3) {
var name = $('#skype').val();
}
else {
errorMsg = 'Please Skype name' + '/n';
valid = 1;
}
if ($('#Countries-leagues').val().length > 5) {
var cl = $('#Countries-leagues').val()
}
else {
errorMsg = 'Please enter Coverage' + '/n';
valid = 1;
}
if ($('#opinion').val().length > 5) {
var opinion = $('#opinion').val()
}
else {
errorMsg = 'Please enter Coverage' + '/n';
valid = 1;
}
if (valid == 0) {
send();
}
}
//**************************************************************************
//** Get desired length and string to chech *
//**************************************************************************
function Send() {
AffiliateData.pType = 'AddAffiliate';
AffiliateData.user[0].recomanderId = "1"
AffiliateData.user[0].userName = $('#fullName').val();
AffiliateData.user[0].email = $('#email').val();
AffiliateData.user[0].skype = $('#skype').val();
AffiliateData.user[0].covered = $('#Countries-leagues').val();
AffiliateData.user[0].opinion = $('#opinion').val();
if ($('#canConnect').is(":checked")) {
AffiliateData.user[0].canContact = "1";
}
else {
AffiliateData.user[0].canContact = "0";
}
if ($('#aware').is(":checked")) {
AffiliateData.user[0].aware = "1";
}
else {
AffiliateData.user[0].aware = "0";
}
$.ajax({
type: "POST",
processData: false,
url: "http://localhost/MVC%205%20Skeleton1/AddAffilate/Create/1",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({ json: AffiliateData }),
// dataType: "json",
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
}
//**************************************************************************
//** Clean UI Fields *
//**************************************************************************
function clearFields() {
$('#fullName').val("");
$('#email').val("");
$('#skype').val("");
$('#email').val("");
$('#Countries-leagues').val("");
$('#opinion').val("");
$('input:checkbox').removeAttr('checked');
}
//********************* end of script block *********************
</script>
</head>
<body>
<h2>Create new Affilate</h2>
<fieldset>
<!-- Form Name -->
<!-- Text input-->
<div class="form-group">
<div class="col-md-12">
<label class="control-label" for="textinput">Candidate Name </label>
</div>
<div class="col-md-12">
<input id="fullName" name="textinput" type="text" placeholder="Candidate Name " class="form-control input-md txtW" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="col-md-12">
<label class="control-label" for="email">Email</label>
</div>
<div class="col-md-12">
<input id="email" name="email" type="email" placeholder="Email" class="form-control input-md txtW" required="">
</div>
</div>
<!-- Text input-->
<div class="form-group">
<div class="col-md-12">
<label class="control-label" for="skype">Skype</label>
</div>
<div class="col-md-12">
<input id="skype" name="skype" type="text" placeholder="Skype" class="form-control input-md txtW" required="">
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-12 control-label" for="Countries-leagues">Countries/leagues</label>
<div class="col-md-12">
<textarea class="form-control txtW txtAH" id="Countries-leagues" name="Countries-leagues" required=""></textarea>
</div>
</div>
<!-- Textarea -->
<div class="form-group">
<label class="col-md-12 control-label" for="opinion">Way are you recommending Him/Her</label>
<div class="col-md-4">
<textarea class="form-control txtW txtAH" id="opinion" name="opinion" required=""></textarea>
</div>
</div>
<!-- Multiple Checkboxes -->
<div class="form-group">
<label class="col-md-12 control-label" for="checkboxes"></label>
<div class="col-md-4">
<div class="checkbox">
<label for="checkboxes-0">
<input type="checkbox" name="checkboxes" id="canConnect" value="0">
Can we contact he/she?
</label>
</div>
<div class="checkbox">
<label for="checkboxes-1">
<input type="checkbox" name="checkboxes" id="aware" value="0">
Dose he/she knows will approach them?
</label>
</div>
</div>
</div>
<!-- Button (Double) -->
<div class="form-group">
<label class="col-md-12 control-label" for="submit"></label>
<div class="col-md-8">
<button id="submit" name="submit" class="btn btn-success">Submit</button>
<button id="cancel" name="cancel" class="btn btn-primary">Cancel</button>
</div>
</div>
</fieldset>
</body>
</html>
How can I get to my #model ?
Can I use the data in my Jquery code?
Thanks
You can access your model properties by using #Model.PropertyName.
Example:
<textarea class="form-control txtW txtAH" id="opinion" name="opinion" required="">#Model.opinion</textarea>
Edited: I saw on your question commens on how to access that information with jQuery.
If you follow the previous example, you can access it by simply
$("#opinion").val()

Submit form with jquery ajax

I'm trying to learn MVC and one the things I want to do is submit a form to an action in my controller and this action will return the submitted data. Sounds simple but I've been trying for hours without any success.
my view:
#using (Html.BeginForm("BlogComment","Blog"))
{
#Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
<input type="text" id="username" />
</div>
<div class="editor-text">
<textarea id="comment" rows="6" cols="23"></textarea>
</div>
<div class="editor-field">
<input type="hidden" id="hiddendate" />
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
my controller:
[HttpPost]
public ActionResult CommentForm(Comment comment)
{
Comment ajaxComment = new Comment();
ajaxComment.CommentText = comment.UserName;
ajaxComment.DateCreated = comment.DateCreated;
ajaxComment.PostId = comment.PostId;
ajaxComment.UserName = comment.UserName;
mRep.Add(ajaxComment);
uow.Save();
//Get all the comments for the given post id
return Json(ajaxComment);
}
and my js:
$(document).ready(function () {
$('form').submit(function () {
$.ajax({
url: '#Url.Action("CommentForm")',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
},
success: function (result) {
alert("success " + result.UserName);
},
error: function (result) {
alert("Failed");
}
});
return false;
});
});
You don't need to write any client side code to do this, FYI.
To use the ajax methods successfully in MVC, you will need to do the following. Add this key to appsettings in web.config:
<appSettings>
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
As well as include the unobtrusive ajax script:
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
Then create div container around your form and replace Html.BeginForm with Ajax.BeginForm
<div id="ajaxReplace">
#using (Ajax.BeginForm("BlogComment", "Blog", null, new AjaxOptions { UpdateTargetId = "ajaxReplace", OnSuccess = "doFunctionIfYouNeedTo", OnFailure = "ShowPopUpErrorIfYouWant" }))
{
#Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
<input type="text" id="username" />
</div>
<div class="editor-text">
<textarea id="comment" rows="6" cols="23"></textarea>
</div>
<div class="editor-field">
<input type="hidden" id="hiddendate" />
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
</div>
Then in your controller you'll return something like this:
return PartialView(ajaxComment);
This will save you maintaining a script to do this manually and will funnel you into using the framework as intended. It will also help you out with data annotation validation and all of the juicy stuff that goes with it,
I hope this helps in some way.
Try this:
The Model
public class Comment
{
public string CommentText { get; set; }
public DateTime? DateCreated { get; set; }
public long PostId { get; set; }
public string UserName { get; set; }
}
The View and js
#model SubmitMvcForWithJQueryAjax.Models.Comment
#using (Html.BeginForm("BlogComment","Blog"))
{
#Html.ValidationSummary(true)
<legend class="AddAComment">Add a comment</legend>
<div class="commentformwrapper">
<div class="editor-text">
<span class="editor-label">User Name:</span>
</div>
<div class="editor-text">
#Html.EditorFor(m => m.UserName)
</div>
<div class="editor-text">
#Html.TextAreaFor(m => m.CommentText, new { rows="6", cols="23"} )
</div>
<div class="editor-field">
#Html.HiddenFor(m => m.DateCreated)
</div>
<div class="editor-field">
#Html.HiddenFor(m => m.PostId)
</div>
<input type="submit" id="submit" value="Create" />
</div>
}
<script type="text/javascript">
$(document).ready(function () {
$('form').submit(function () {
var serializedForm = $(this).serialize();
$.ajax({
url: '#Url.Action("CommentForm")',
type: "POST",
data: serializedForm,
success: function (result) {
alert("success " + result.UserName);
},
error: function (result) {
alert("Failed");
}
});
return false;
});
});
</script>
The Controller
public class CommentController : Controller
{
//
// GET: /Comment/
public ActionResult Index()
{
return View(new Comment());
}
[HttpPost]
public ActionResult CommentForm(Comment comment)
{
Comment ajaxComment = new Comment();
ajaxComment.CommentText = comment.UserName;
ajaxComment.DateCreated = comment.DateCreated ?? DateTime.Now;
ajaxComment.PostId = comment.PostId;
ajaxComment.UserName = comment.UserName;
//mRep.Add(ajaxComment);
//uow.Save();
//Get all the comments for the given post id
return Json(ajaxComment);
}
}
Basically you are passing javascript object literals directly. So, before you pass data to your controller, it must be in JSON format(because you have specified application/json. see your $.ajax call).
SO, you are missing JSON.stringify()
data: JSON.stringify({
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
}),
OR
var someObj = {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
};
$.ajax({
/// your other code
data: JSON.stringify(someObj),
// your rest of the code
});
Instead of
data: {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
},
Try
$('form').submit(function () {
var obj = {
PostId: $('.postid').val(),
UserName: $('#username').val(),
DateCreated: new Date(),
CommentText: $('#comment').val()
};
$.ajax({
...,
data: JSON.stringify(obj),
...,
});
return false;
});
You have to convert data to string before sending it to server. and JSON.stringify does that job

Categories

Resources