.NET MVC 4 list with KnockoutJS data-bind'ing - asp.net

Ok so i have a view with this so far
function AppViewModel() {
this.title = ko.observable("#Model.Title");
this.firstName = ko.observable("#Model.FirstName");
this.lastName = ko.observable("#Model.LastName");
this.fullName = ko.computed(function () {
return this.title() + " " + this.firstName() + " " + this.lastName();
}, this);
}
#{
var jsList = Html.Raw(JsonConvert.SerializeObject(ViewBag.Countries));
}
function newViewModel() {
var theAppViewModel = new AppViewModel()
var g = ko.mapping.fromJS(theAppViewModel);
var viewModel = { vm: ko.observable([]) }
viewModel.vm = ko.mapping.fromJS(#jsList);
ko.applyBindings(g);
}
// Activates knockout.js
$(document).ready(function () {
ko.applyBindings(new newViewModel());
});
<ul style="list-style-type: none; float: left; margin-top: 20px; ">
<li>
#Html.LabelFor(model => model.Title)
<input data-bind="value: title"/>
</li>
<li>
#Html.LabelFor(model => model.FirstName)
<input data-bind="value: firstName" />
</li>
<li>
#Html.LabelFor(model => model.LastName)
<input data-bind="value: lastName" />
</li>
<li>
Full Name
<Span data-bind="text: fullName"></Span>
</li>
<li>
Coutries:
<select data-bind="foreach: vm">
<option data-bind="text: CountryName"></option>
</select>
</li>
</ul>
My Controller has this on it,
public ActionResult Index()
{
//ViewBag.Message = "KO js in mvc 4";
ViewBag.Countries = new List<Country>(){
new Country()
{
Id = 1,
CountryName = "America",
Abbreviation = "USA"
},
new Country()
{
Id = 2,
CountryName = "United Kingdon",
Abbreviation = "UK"
},
new Country()
{
Id = 3,
CountryName = "Irland",
Abbreviation = "IRL",
}
};
var vm = new PersonViewModel()
{
Id = 1,
DateOfBirth = new DateTime(1993, 01, 22),
Title = "Miss",
FirstName = "Jamie",
LastName = "Oscar",
};
return View(vm);
}
I can return the List from the controller in a standard loop like this:
<select>
#foreach(var c in ViewBag.Countries)
{
<option>#c.CountryName</option>
}
</select>
But I would like to bind the results to the list Via Knockout.js.

Your current viewModel that is containing the countries list is not bound, the only bound View-Model is the g you're calling applyBinding() with. Also, there's no point calling applyBinding() twice (on the same element).
Try this instead:
$(document).ready(function() {
var vm = new AppViewModel();
vm.Countries = ko.mapping.fromJS(#jsList);
ko.applyBindings(vm);
});
<select data-bind="value: countryId,
options: Countries,
optionsText: 'CountryName',
optionsValue: 'Id'"></select>
Please keep in mind that the value directive is referring to the chosen CountryId of the person but you currently don't have such a field in your View-Model.
Consider adding it as well:
var vm = new PersonViewModel()
{
Id = 1,
DateOfBirth = new DateTime(1993, 01, 22),
Title = "Miss",
FirstName = "Jamie",
LastName = "Oscar",
CountryId = 1
};
function AppViewModel() {
this.title = ko.observable("#Model.Title");
this.firstName = ko.observable("#Model.FirstName");
this.lastName = ko.observable("#Model.LastName");
this.countryId = ko.observable(#Model.CountryId);
}

it has now come to my attention that I can now bind knockout Json result to a #html.DropDownListFor attribute helper and still bind my data from knockout I have a DropDown list that is populated by knockout json array object, but then also bind this to the MVC 4 model this can be then used in the controller and the passed back to WCF or Linq to SQL for database
#Html.DropDownListFor(m => m.SelectedAuthType,
(SelectList)Model.authlevellistItems,
new { id = "alddl", data_bind = " options: Countries, optionsText: 'CountryName', optionsValue: 'Id'" })
works perfectly with models now as well as JSON knockout results.

Related

How can i get Kendo Grid DataItem

How can i get the selected row KendoGrid Data Item?
I research a lot online and I came across this post http://dojo.telerik.com/egUpI which does exactly what i am looking for i would like implement the same.
I have the following code to populate grid in asp.net view. I need your help when row selected populate a elements.
Here is my Grid View:
<h1> Contacts</h1>
#{
var gridColumnSettings = new List<GridColumnSettings>
{
new GridColumnSettings
{
Member = nameof(Contact.Name),
MemberType = typeof(string)
},
new GridColumnSettings
{
Member = nameof(Contact.PhoneNumber),
MemberType = typeof(string)
}
};
var gridViewModel = new GridViewModel
{
Name = "ContactGrid", // Grid Name
Columns = gridColumnSettings,
AutoBind = true,
DataSourceSettings = new GridDataSourceSettings
{
ReadDataSource = new DataSourceSetting()
{
ActionName = "Contact",
ControllerName = "Contact",
HttpVerb = HttpVerbs.Get,
}
},
SelectionSettings = new GridSelectionSettings
{
IsSelectable = true, // To make grid selectable
GridSelectionMode = 0,
GridSelectionType = 0
},
}
};
}
Here is my Form on the same Page to display the selected grid row information
<form>
<h3>Name</h3>
<div class="col-sm-3">
<input type="text" readonly class="form-control " id="Name">
</div>
<h3>Phone</h3>
<div class="col-sm-3">
<input type="text" readonly class="form-control" id="Phone">
</div>
</form>
I tried this Jquery, but not working
<script>
function fillForm() {
$("#ContactGrid").kendoGrid({
change: function (e) {
var dataItem = this.dataItem(this.select());
fillForm(dataItem);
}
});
}
// Fill Form based on the selected row
var fillForm = function(dataItem) {
var columns = $("#ContactGrid").data("kendoGrid").options.columns;
var form = $("form");
for (var i = 0; i < columns.length; i++) {
var field = columns[i].field;
form.find("#" + field).val(dataItem[field]);
}
}
</script>

Changing number of table elements displayed on page resets my search results

I have numerous data displayed in a table, let's say a long list of users (first name & last name), so I set up a paging feature to display the elements by pages via the PagedList NuGet package. I was inspired by this tutorial: https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application
I implemented a drop-down list in my view, so that I can directly choose the number of elements to display per page. I managed to include a jQuery script that makes the page size update whenever the drop-down list has a new selected value.
Using the mentioned tutorial , I also added a search feature: submitting a string in a search form allows to filter the data.
My problem is: changing the page size by selecting a new value in the drop-down list after having done a search doesn't work: the search results are reset, all the entries being displayed instead. I guess I forgot to pass some parameter somewhere but I just can't figure out where...
Here is my controller:
public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page, int? PageSize)
// Sort order is passed to view in order to keep it intact while clicking in another page link
ViewBag.CurrentSort = sortOrder;
// Ascending or descending sorting by first or last name according to sortOrder value
ViewBag.LastNameSortParm = String.IsNullOrEmpty(sortOrder) ? "lastname_desc" : "";
ViewBag.FirstNameSortParm = sortOrder == "firstname" ? "firstname_desc" : "firstname";
// Not sure here
if (searchString == null)
{
searchString = currentFilter;
}
// Pass filtering string to view in order to maintain filtering when paging
ViewBag.CurrentFilter = searchString;
var users = from u in _db.USER select u;
// FILTERING
if (!String.IsNullOrEmpty(searchString))
{
users = users.Where(u => u.lastname.Contains(searchString)
|| u.firstname.Contains(searchString)
}
// Ascending or descending filtering by first/last name
switch (sortOrder)
{
case "lastname": // Ascending last name
users = users.OrderBy(u => u.lastname);
break;
case "lastname_desc": // Descending last name
users = users.OrderByDescending(u => u.lastname);
break;
case "firstname": // Ascending first name
users = users.OrderBy(u => u.firstname);
break;
case "firstname_desc": // Descending first name
users = users.OrderByDescending(u => u.firstname);
break;
default:
users = users.OrderBy(u => u.lastname);
break;
}
// DROPDOWNLIST FOR UPDATING PAGE SIZE
int count = _db.USER.OrderBy(e => e.Id).Count(); // Total number of elements
// Populate DropDownList
ViewBag.PageSize = new List<SelectListItem>() {
new SelectListItem { Text = "10", Value = "10", Selected = true },
new SelectListItem { Text = "25", Value = "25" },
new SelectListItem { Text = "50", Value = "50" },
new SelectListItem { Text = "100", Value = "100" },
new SelectListItem { Text = "All", Value = count.ToString() }
};
int pageNumber = (page ?? 1);
int pageSize = (PageSize ?? 10);
ViewBag.psize = pageSize;
return View(users.ToPagedList(pageNumber, pageSize));
}
And my Index.cshtml view:
<script src="~/Scripts/jquery-3.2.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () { // Submit pageSizeForm when another pageSize value is selected
$("#pageSize").change(function () {
$("#pageSizeForm").submit();
});
});
</script>
#model PagedList.IPagedList<AfpaSIPAdmin.Models.USER>
#using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
#{
ViewBag.Title = "Users management";
}
<h1>Users management</h1>
<!-- Creating a new entry in table -->
<p>
#Html.ActionLink("Create new user", "Create")
</p>
<!-- Filtering table entries -->
#using (Html.BeginForm("Index", "Users", FormMethod.Get, new { id = "filterForm" }))
{
<p>
Filter: #Html.TextBox("SearchString", ViewBag.CurrentFilter as string, new { #placeholder = "First or last name..." })
<input type="submit" value="Apply"/>
</p>
}
<!-- Display table -->
<table class="table">
<tr>
<th>
#Html.ActionLink("Last name", "Index", new {
sortOrder = ViewBag.LastNameSortParm,
currentFilter = ViewBag.CurrentFilter
})
</th>
<th>
#Html.ActionLink("First name", "Index", new {
sortOrder = ViewBag.FirstNameSortParm,
currentFilter = ViewBag.CurrentFilter
})
</th>
<th style="min-width: 170px"></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td style = "min-width: 150px">
#Html.DisplayFor(modelItem => item.lastname)
</td>
<td style = "min-width: 150px">
#Html.DisplayFor(modelItem => item.firstname)
</td>
<td> <!-- Using images as buttons for actions -->
<a href="#Url.Action("Edit", "Users", new { id = item.Id })" title="Edit">
<img src="~/Content/images/edit.gif" />
</a>
<a href="#Url.Action("Details", "Users", new { id = item.Id })" title="Details">
<img src="~/Content/images/info.gif" />
</a>
<a href="#Url.Action("Delete", "Users", new { id = item.Id })" title="Delete">
<img src="~/Content/images/delete.gif" />
</a>
</td>
</tr>
}
</table>
<br/>
<!-- Paging -->
#using (Html.BeginForm("Index", "Users", FormMethod.Get, new { id = "pageSizeForm" }))
{
<div class="pager">
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) sur #Model.PageCount<br/>
#Model.Count of #Model.TotalItemCount elements
#Html.PagedListPager(Model, page => Url.Action("Index", new {
page,
sortOrder = ViewBag.CurrentSort,
currentFilter = ViewBag.CurrentFilter,
searchString = ViewBag.CurrentFilter,
pageSize = ViewBag.psize
}))
<!-- DropDownList for setting page size -->
Elements per page :
#Html.DropDownList("pageSize")
</div>
}
The reason is because you have 2 forms. When you submit the first form containing the textbox, the only value you send back to the controller is SearchString and all the other parameters in your method will be their default (for example when you return the view, PageSize will default to null and therefore return only 10 records even if the user previously selected say 50.
Likewise, when you submit the 2nd form containing dropdownlist for the page size, the value of SearchString will be null because its not sent in the request.
You need to have one form only containing both form controls. And if you wanted to send additional properties, for example the current sort order, then you can add those as query string values in the form element (for example, #using(Html.BeginForm("Index", "Users", new { sortOrder = .... }, FormMethod.Get))
I would also strongly recommend you use a view model containing the properties you need in the view and strongly bind to them rather than using ViewBag
public class UsersVM
{
public string SearchString { get; set; }
public int PageSize { get; set; }
public IEnumerable<SelectListItem> PageSizeOptions { get; set; }
.....
public IPagedList<USER> Users { get; set; }
}
View
#model UsersVM
...
#using(Html.BeginForm("Index", "Users", FormMethod.Get))
{
#Html.LabelFor(m => m.SearchString)
#Html.TextBoxFor(m => m.SearchString)
#Html.LabelFor(m => m.PageSize)
#Html.DropDownListFor(m => m.PageSize, Model.PageSizeOptions)
<input type="submit" value="Filter" />
}
....
<div class="pager">
Page #(Model.Users.PageCount < Model.Users.PageNumber ? 0 : Model.Users.PageNumber)
....
#Html.PagedListPager(Model.Users, page => Url.Action("Index", new {
page,
sortOrder = Model.CurrentSort,
currentFilter = Model.CurrentFilter,
searchString = Model.CurrentFilter,
pageSize = Model.PageSize
}))
</div>
and in the controller method, initialize a new instance of UsersVM and assign its properties
public ActionResult Index(string sortOrder, string currentFilter, string searchString, int? page, int? pageSize)
{
UsersVM model = new UsersVM();
....
var users = from u in _db.USER select u;
....
pageSize = pageSize ?? 10;
model.PageSize = pageSize.Value;
model.Users = users.ToPagedList(pageNumber, pageSize);
model.PageSizeOptions = new List<SelectListItem> { .... };
return View(model);
}

Updating column in ASP.NET mvc 5 creates new row

I'm following this tutorial to create a modified version of a blog. In this case, the "posts" are the same things as "projects," the "tags" are called "technologies," and the comments are all the same. In this case, the create new post/project function also should be able to update existing posts/projects. When I click submit, however, editing an old post, it simply creates a new one.
Here is my controller:
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
[ValidateInput(false)]
public ActionResult Update(int? p, string title, string shortDescription, string longDescription, DateTime dateTime, string technologies)
{
Project project = GetProject(p);
if (!User.IsInRole("ChapterAdvisor") || !(User.Identity.GetFirstName() + " " + User.Identity.GetLastName()).Equals(project.ProjectLeader))
{
RedirectToAction("Index");
}
project.Title = title;
project.ShortDescription = shortDescription;
project.LongDescription = longDescription;
project.TimeCreated = dateTime;
project.ProjectLeader = User.Identity.GetFirstName() + " " + User.Identity.GetLastName();
project.Technologies.Clear();
technologies = technologies ?? string.Empty;
string[] technologyNames = technologies.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries);
foreach (string technologyName in technologyNames)
{
project.Technologies.Add(GetTechnology(technologyName));
}
if (!p.HasValue)
{
model.Projects.Add(project);
}
try
{
model.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
// raise a new exception nesting
// the current instance as InnerException
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("Details", new { p = project.Id });
}
public ActionResult Edit(int? p)
{
Project project = GetProject(p);
StringBuilder technologyList = new StringBuilder();
foreach (Technology technology in project.Technologies)
{
technologyList.AppendFormat("{0} ", technology.Name);
}
ViewBag.Technologies = technologyList.ToString();
return View(project);
}
private Technology GetTechnology(string technologyName)
{
return model.Technologies.Where(x => x.Name == technologyName).FirstOrDefault() ?? new Technology() { Name = technologyName };
}
private Project GetProject(int? id) => id.HasValue ? model.Projects.Where(x => x.Id == id).First() : new Project() { Id = -1 };
And this is my view:
<form action="#Href("~/Projects/Update")" method="post" id="postForm">
#Html.AntiForgeryToken()
#if (Model.Id != -1)
{
<input type="hidden" value="#Model.Id" />
}
#{ DateTime dateTime = Model.TimeCreated.Year > 2000 ? Model.TimeCreated : DateTime.Now; }
<input type="text" name="dateTime" value="#dateTime" /> Date<br />
<input type="text" name="title" value="#Model.Title" /> Project Name<br />
#Html.DropDownListFor(m => m.Technologies, new SelectList(new List<Object> { new { value = "Animation", text = "Animation" }, new { value = "Robotics", text = "Robotics" }, new { value = "Architecture", text = "Architecture" }, new { value = "CAD", text = "CAD" }, new { value = "Websites", text = "Websites" }, new { value = "Games", text = "Games" }, new { value = "Biotechnology", text = "Biotechnology" }, new { value = "Club", text = "Club" }, new { value = "Other", text = "Other" } }, "value", "text"), new { #style = "border: 1px solid #e8e8e8;padding: 0.5em 1.07em 0.5em;background: #f5f5f5;font-size: 0.875rem;border-radius: 5px;width: 100%;line-height: 1.43;min-height: 3.5em;" })
<textarea name="shortDescription" rows="5" cols="80">#Model.ShortDescription</textarea><br />
<textarea name="longDescription" rows="10" cols="80">#Model.LongDescription</textarea><br />
<input type="submit" name="submit" value="Save Changes" />
</form>
Any ideas why it is creating a new "project" instead of updating the one defined by the variable passed in the url?
Every post from that form is being treated as a "new" record because it doesn't contain the ID from an existing record. So the logic always assumes it's new.
This is because the hidden input isn't included in the POST data because it has no name:
<input type="hidden" value="#Model.Id" />
It looks like your action expects the ID value to be called "p":
<input type="hidden" name="p" value="#Model.Id" />

Display same data again and again in asp.net mvc

This is my LINQ code:
public JsonResult getfull()
{
var coursename = Session["course"].ToString();
var location = Session["location"].ToString();
var result = (from insti in db.Institute_Master
join course in db.Course_Detail on insti.InstituteId equals course.InstituteId
join coursemaster in db.Course_Master on course.CourseId equals coursemaster.CourseId
join facility in db.Facility_Detail on insti.InstituteId equals facility.InstituteId
join masterfacility in db.Facility_Master on facility.FacilityMasterID equals masterfacility.FacilityMasterId
where coursemaster.CourseName == coursename || insti.City == location
select new
{
//Id = insti.InstituteId,
name = insti.InstituteName,
university = insti.University,
Contact = insti.ContactNo,
address = insti.Address,
email = insti.EmailId,
zipcode = insti.Zipcode,
country = insti.Country,
state = insti.State,
city = insti.City,
start = insti.EstablishOn,
image = insti.ProfilePhoto,
fees = course.TotalFees,
mode = course.Mode,
coursename = coursemaster.CourseName,
duaration = coursemaster.duration,
discription = coursemaster.Discription,
eligibility = coursemaster.Eligibility,
recognization = coursemaster.Recognization,
facility = masterfacility.FacilityName
}).Distinct();
ViewBag.facilies = list;
return Json(result, JsonRequestBehavior.AllowGet);
}
This method is return json result which is handled by angular js and I mention angularjs code below.
I am using AngularJs To display a data and my record is repeating for particular facility.
This is my tables:
This is a problem that display same record again for his facility:
This is my Angularjs code
<h1>Show Institute</h1>
<div data-ng-app="myModule">
<div data-ng-controller="myController">
<ul class="w3-ul w3-card-4" data-ng-repeat="detail in employees">
<li class="w3-padding-16 institute-list">
<span class="w3-xlarge">{{detail.name | uppercase}}</span>,<span>{{detail.address}}</span><br>
<img alt="image" src="~/images/{{detail.image}}" class="w3-left w3-margin-right img-institute-list" style="width:60px" />
<span class="w3-xlarge">{{detail.coursename | uppercase}}</span>,<span>Course Duration {{detail.duaration}}</span>,<span>Course Mode {{detail.mode}}</span>,<span>{{detail.discription}}</span><br>
<span><b>Fees : </b>INR {{detail.fees}}</span><br>
<span><b>{{detail.recognization | uppercase}}</b> Recognised</span><br>
<span>Facility {{detail.facility}}</span>
<button class="w3-btn w3-blue" id="detail">More Details</button>
</li>
<script>
$(document).ready(function () {
$("button").click(function () {
$("#moredetail").toggle();
});
});
</script>
<li class="w3-padding-16 institute-list" id="moredetail" style="display:none">
<span class="w3-xlarge">{{detail.contact}}</span> <span class="w3-xlarge">{{detail.email}}</span><br />
<span class="w3-xlarge" >{{detail.zipcode}}</span> <span class="w3-xlarge" >{{detail.country}}</span> <br/>
<span class="w3-xlarge" >{{detail.state}}</span> <span class="w3-xlarge" >{{detail.city}}</span> <br />
<span class="w3-xlarge" >{{detail.start}}</span>,
</li>
</ul>
</div>
</div>
<script>
var app = angular
.module("myModule", [])
.controller("myController", function ($scope, $http) {
$http.get("/home/getfull")
.then(function (response) {
$scope.employees = response.data;
});
})
</script>
</div>
</body>
</html>
This code is for displaying data in a view view json method
Can anyone help me in this?
It keeps adding the same record because you have "select new". What you need is model like:
public class CourseModel
{
public int InstituteId {get; set;}
public string InstituteName {get; set;}
public string University {get; set;}
ETC...
}
Then in your MVC Controller:
var result = (from insti in db.Institute_Master
join course in db.Course_Detail on insti.InstituteId equals course.InstituteId
join coursemaster in db.Course_Master on course.CourseId equals coursemaster.CourseId
join facility in db.Facility_Detail on insti.InstituteId equals facility.InstituteId
join masterfacility in db.Facility_Master on facility.FacilityMasterID equals masterfacility.FacilityMasterId
where coursemaster.CourseName == coursename || insti.City == location
var courses = new List<CourseModel>();
foreach(var c in result)
{
courses.Add(new CourseModel
{
InstitueName = insti.InstituteName,
University = insti.University,
ETC...
});
}
return Json(courses, JsonRequestBehavior.AllowGet;
}
I hope this helps!

ASP.NET MVC4 + Get drop down value after HttpPost submit

So I want to get a value of the dropdown (== id of the account) to insert a new transaction
Here below you can find my View:
<div id="content">
<h2>Overschrijving</h2>
<p id="topmsg">velden met een * zijn verplicht</p><p> </p>
<dl class="clearfix form">
#using (Html.BeginForm(new { ReturnUrl = ViewBag.ReturnUrl })) {
#Html.ValidationSummary(true, "Gelieve alles correct in te vullen.")
<dt>#Html.Label("Rekening: *")</dt>
<dd>#Html.DropDownList("ddlAccounts")</dd>
<dt>#Html.Label("Begunstigde: *")</dt>
<dd>#Html.TextBox("ToAccountNumber")</dd>
<dt>#Html.Label("Bedrag: *")</dt>
<dd>#Html.TextBox("Amount", null, new { #class = "inpshort" })</dd>
<dt>#Html.Label("Mededeling: ")</dt>
<dd>#Html.TextBox("Message", null, new { #class = "inplong" })</dd>
<dd class="buttons">
<input type="submit" value="Bevestigen" />
<input type="submit" value="Annuleren" />
</dd>
}
</dl>
</div>
this is the Controller code:
public ActionResult Transfer(int? id) {
Holder h = Holder.GetHolderByHolderId(Convert.ToInt32(User.Identity.Name));
List<Account> holderAccounts = Account.GetAccountsByHolderId(h.Id);
List<SelectListItem> ddlHolderAccounts = new List<SelectListItem>();
ddlHolderAccounts.Add(new SelectListItem { Text = "selecteer...", Value = "-1", Selected = true });
foreach (Account acc in holderAccounts) {
if (acc.Id == id) {
ddlHolderAccounts.Add(new SelectListItem { Text = acc.Name, Value = acc.Id.ToString(), Selected = true });
} else {
ddlHolderAccounts.Add(new SelectListItem { Text = acc.Name, Value = acc.Id.ToString() });
}
}
ViewData["ddlAccounts"] = ddlHolderAccounts;
return View();
}
[HttpPost]
public ActionResult Transfer(Transaction tra) {
if (ModelState.IsValid) {
Transaction.InsertTransaction(tra.Amount, tra.Message, tra.FromAccountId, tra.ToAccountNumber);
}
return View(tra);
}
Now I searched a lot with Google, it's probably better to use the DropDownListFor to fill your drop down list? But could anyone show me an example?
By looking at your code, I can see that you're not passing a list of SelectListItems to the DropDownList helper. You can do this one of two ways.
1- Bind it to a property on your model:
#Html.DropDownListFor(x=>Model.Property, new List<SelectListItem> { new SelectListItem { Text = "Item1", Value = "Value1" })
Or
2- You can do it without binding to a model property like:
#Html.DropDownList("propertyName", new List<SelectListItem> { new SelectListItem { Text = "Item1", Value = "Value1" } })
If you're using the second approach then your controller action must accept "propertyName" as a parameter when submitting.
And don't forget to provide a list of SelectListItems to select from (which you're not doing in your code).
Hope this helps.
should be
#Html.DropDownListFor(x=>Model.Property, new List { new SelectListItem { Text = "Item1", Value = "Value1" }})

Resources