I have a search screen which gives the results in a paged list. On changing the page I need to get the values of the Model to the GET method in the controller. While I was able to pass the model properties which are strings, I am having an issue passing the string list.
View Code :
<div class="divSearch">
<div class="divCriteria">
<div class="row">
<div class="col-md-6">
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name, new { #class = "form-control" })
</div>
<div class="col-md-6">
#Html.LabelFor(m => m.Owner)
#Html.TextBoxFor(m => m.Owner, new { #class = "form-control" })
</div>
</div>
<br />
<div class="row">
<div class="col-md-6">
#Html.LabelFor(m => m.County)
#Html.ListBoxFor(model => model.County, Model.CountiesList, new { #class = "form-control", multiple = "multiple" })
</div>
</div>
<br />
<div class="row">
<div class="right">
<button type="submit" class="btn btn-primary"><i class="fa fa-share-square-o"></i>Search</button>
</div>
</div>
</div>
<div class="divResults">
<div class="table-responsive">
<table class="table table-hover table-advance dataTable">
<thead>
<tr>
<th style="display:none">ID</th>
<th>Name</th>
<th>Type</th>
<th>County</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.SearchList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
#Html.HiddenFor(modelItem => item.ID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Type)
</td>
<td>
#Html.DisplayFor(modelItem => item.County)
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
#if (Model.SearchList != null)
{
var county = new List<string>();
foreach (var item in Model.County)
{
county.Add(item);
}
#Html.PagedListPager(Model.SearchList, Page => Url.Action("Index", "FacilityFinder", new RouteValueDictionary() { { "Page", Page }, { "name", Model.Name }, { "owner", Model.Owner }, { "county", county} }),PagedListRenderOptions.PageNumbersOnly)
}
Controller code :
public ActionResult Index(int? page=null,string name = null, List<string> county=null,string owner = null)
{
}
The value for name and owner are fine in the controller, but the list of county gives me System.Collections.Generic.List`1[System.String]
Am I missing something?
You can't pass complex types such as lists. You might need to construct your RouteValueDictionary dynamically:
var query = new RouteValueDictionary
{
{ "name", Model.Name },
{ "owner", Model.Owner }
};
for (var i = 0; i < Model.County.Count; i++)
{
query["county[" + i + "]"] = Model.County[i];
}
#Html.PagedListPager(
Model.SearchList,
Page => Url.Action("Index", "FacilityFinder", new RouteValueDictionary(query) { { "Page", Page } }),
PagedListRenderOptions.PageNumbersOnly
)
so that the resulting url looks like this:
/FacilityFinder/Index?Page=5&name=Foo&owner=Bar&county[0]=foo1&county[1]=foo2...
which will make the default model binder in ASP.NET MVC happy and properly bind this to a List<string>.
Related
This is Schedule Exam service:
public int AddSchedule(ScheduleExamViewModel schedule)
{
var newSchedule = new ScheduleExam()
{
ExamDate = schedule.ExamDate,
SubjectId = schedule.SubjectId,
StudentId = schedule.StudentId,
Status = schedule.Status
};
_context.ScheduleExams.Add(newSchedule);
_context.SaveChanges();
return newSchedule.Id;
}
This is Schedule exam controller :
// GET: ScheduleExamController/Create
public IActionResult Create()
{
var model = new ScheduleExamViewModel();
ViewBag.Subject = new SelectList(_isubject.GetSubject(), "Id", "Name");
ViewBag.Student = new SelectList(_istudent.GetStudent(), "Id", "Name");
return View(model);
}
// POST: ScheduleExamController/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(ScheduleExamViewModel schedule)
{
if (ModelState.IsValid)
{
int id = _ischeduleExam.AddSchedule(schedule);
if (id > 0)
{
return RedirectToAction(nameof(Create));
}
}
ViewBag.Subject = new SelectList(_isubject.GetSubject(), "Id", "Name");
ViewBag.Student = new SelectList(_istudent.GetStudent(), "Id", "Name");
return View(schedule);
}
I want to get the Id of student and save it to table of schedule exam by clicking on the "Schedule New Exam"
This is the index.cshtml of the Student table:
<table class="table table-hover table-bordered table-condensed">
<thead class="table-color text-white">
<tr>
<th>
#Html.DisplayNameFor(model => model.Id)
</th>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.LastName)
</th>
<th>
#Html.DisplayNameFor(model => model.Email)
</th>
<th>Schedule New Exam</th>
<th>Properties</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
<a asp-action="Create" asp-controller="ScheduleExam", asp-route-id="#item.Id">Schedule New Exam</a>
</td>
<td>
#Html.ActionLink(" ", "Edit", new { id = item.Id }, new { #class = "fa fa-edit", title = "Edit" }) |
#Html.ActionLink(" ", "Details", new { id = item.Id }, new { #class = "fa fa-info-circle", title = "More details" }) |
#Html.ActionLink(" ", "Delete", new { id = item.Id }, new { #class = "fa fa-trash", title = "Delete" })
</td>
</tr>
}
</tbody>
</table>
and this is the create.csthml page of schedule exam:
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="ExamDate" class="control-label"></label>
<input asp-for="ExamDate" class="form-control" />
<span asp-validation-for="ExamDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="StudentId" class="control-label"></label>
<input asp-for="StudentId" class="form-control" value="#ViewBag.model.Id" />
<span asp-validation-for="StudentId" class="text-danger"></span>
</div>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><strong>Subject:</strong></span>
</div><br />
<select asp-for="SubjectId" class="form-control input-hover" asp-items="ViewBag.Subject">
<option value="">Please choose a subject...</option>
</select>
<span asp-validation-for="SubjectId " class="text-danger"></span>
</div><br />
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
but when I click on the Schedule New exam in index.cshtml of Student table I get this error:
RuntimeBinderException: Cannot perform runtime binding on a null reference
CallSite.Target(Closure , CallSite , object )
CallSite.Target(Closure , CallSite , object )
System.Dynamic.UpdateDelegates.UpdateAndExecute1<T0, TRet>(CallSite site, T0 arg0)
AspNetCore.Views_ScheduleExam_Create.b__22_0() in Create.cshtml
+
<input asp-for="StudentId" class="form-control" value="#ViewBag.model.Id" />
Please solve it by details and I'm using ASP.NET Core 3.1 MVC using a repository pattern.
Thank you
first of all, you should get an Id inside Create-Action and set for students :
public IActionResult Create(int Id)
{
var model = new ScheduleExamViewModel();
ViewBag.Subject = new SelectList(_isubject.GetSubject(), "Id", "Name");
ViewBag.Student = new SelectList(_istudent.GetStudent(), "Id", "Name" , Id);
return View(model);
}
Second, I can't find a drop-down list for Students in your view. I think you should set Id in the controller for ViewModel.
var model = new ScheduleExamViewModel();
mode.Id = Id;
Third, you passed a model to the View and you can get information from the Model.
#model ScheduleExamViewModel
<input asp-for="StudentId" class="form-control" value="#Model.Id" />
I need to switch two different models in one view.
For that, I created a class that contains my two "subclasses" of my models.
So far so good, my problem is in converting these classes to .ToList(), I have an error that tells me that I can not convert a List<Events> into Events (which I understand perfectly).
Except that if in my main class (EventViewModel) I change and I say that my subclasses are lists, then when I go in my view I do not parivens more to access the elements of my subclasses.
Indeed, I have for example a #Html.LabelFor(model => model._Events.) Except that there is no way to find the desired element of my object, since it represents a list.
I still specify that results is of type IEnumerable and also that I need to recover several events by request.
To do this, I used this page (Two models in one view in ASP MVC 3), especially the second answer.
Controller
[Authorize]
[HttpGet]
public async Task<ActionResult> Index()
{
ViewBag.sessionv = HttpContext.Session.GetInt32("idMember");
FileMakerRestClient client = new FileMakerRestClient(serverName, fileName, userName, password);
var toFind = new Models.EventsLines { Zkf_CTC = 1053 };
var results = await client.FindAsync(toFind);
Models.EventViewModel oEventViewModel = new Models.EventViewModel
{
_EventsLines = (from o in results select o).ToList()
};
ViewBag.JsonList = oEventViewModel;
return View(oEventViewModel);
}
[Authorize]
[HttpGet]
public async Task<ActionResult> GetEventsDetails(int Id_Event, int Id_CTC)
{
ViewBag.sessionv = HttpContext.Session.GetInt32("idMember");
FileMakerRestClient client = new FileMakerRestClient(serverName, fileName, userName, password);
var toFind = new Models.SubEventsLines { Zkp_WEB_SEL = ViewBag.sessionv, Zkf_CTC = Id_CTC, Zkf_EVL = Id_Event };
var results = await client.FindAsync(toFind);
Models.EventViewModel oEventViewModel = new Models.EventViewModel
{
_SubEventsLines = (from o in results select o).ToList()
};
Console.WriteLine(oEventViewModel);
return Json(oEventViewModel);
}
public class EventViewModel
{
public Events _Events { get; set; }
public SubEvents _SubEvents { get; set; }
}
**View**
#model jak.formulaire.Models.EventViewModel
<div class="container">
<div class="col-5" style="margin-top:2%">
<h3>Registration History</h3>
</div>
#* Table of Events member *#
<div>
<table id="example" class="table table-hover" style="width:100%; margin-top:2%">
<thead>
<tr>
<th scope="col">Event Name</th>
<th scope="col">Start Date</th>
<th scope="col">End Date</th>
<th scope="col">Status</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model._EventsLines)
{
<tr>
<td>#item.Event_Name</td>
<td>#item.Event_DateStart</td>
<td>#item.Event_DateEnd</td>
<td>#item.Event_Status</td>
<td>View Details</td>
</tr>
}
</tbody>
</table>
</div>
</div>
#* Modal Details *#
<div class="modal" role="dialog" id="myModal">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalTitle">Details : </h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div id="myModalContent">
<div class="container" style="width:auto; margin-top:1%">
<div class="row col-12">
#foreach (var item in Model._EventsLines)
{
<div class="form-horizontal col-6" style="margin-left:-5%">
#Html.HiddenFor(model => model._EventsLines.FirstOrDefault().Zkp, new { data_val = "false" })
#Html.HiddenFor(model => model._EventsLines.FirstOrDefault().Zkf_CTC, new { data_val = "false" })
<div class="form-check-inline col-12" style="margin-top:1%">
<label class="control-label col-md-5" style="font-size:13px">Start Date</label>
<input name="Event_StartDate" id="Event_StartDate" value="#item.Event_Name" class="form-control col-md-7" readonly="" />
#*#Html.EditorFor(model => model._Events.FirstOrDefault().Event_Name, new { htmlAttributes = new { #class = "form-control col-md-7", #style = "font-size:13px, height:10px", #readonly = "", #placeholder = "Date Start", #id = "Event_StartDate" } })*#
</div>
<div class="form-check-inline col-12" style="margin-top:1%">
<label class="control-label col-md-5" style="font-size:13px">End Date</label>
#Html.EditorFor(model => model._EventsLines.FirstOrDefault().Event_DateEnd, new { htmlAttributes = new { #class = "form-control col-md-7", #style = "font-size:13px, height:10px", #readonly = "", #placeholder = "Date End", #id = "Event_EndDate" } })
</div>
<div class="form-check-inline col-12" style="margin-top:1%">
<label class="control-label col-md-5" style="font-size:13px">City</label>
#Html.EditorFor(model => model._EventsLines.FirstOrDefault().Event_City, new { htmlAttributes = new { #class = "form-control col-md-7", #style = "font-size:13px, height:10px", #readonly = "", #placeholder = "City", #id = "Event_City" } })
</div>
<div class="form-check-inline col-12" style="margin-top:1%">
<label class="control-label col-md-5" style="font-size:13px">Country</label>
#Html.EditorFor(model => model._EventsLines.FirstOrDefault().Event_Country, new { htmlAttributes = new { #class = "form-control col-md-7", #style = "font-size:13px, height:10px", #readonly = "", #placeholder = "Country", #id = "Event_Country" } })
</div>
</div>
<div class="form-horizontal col-6">
<div class="form-check-inline col-12" style="margin-top:1%">
<label class="control-label col-md-5" style="font-size:13px">Type</label>
#Html.EditorFor(model => model._EventsLines.FirstOrDefault().Event_Type, new { htmlAttributes = new { #class = "form-control col-md-7", #style = "font-size:13px, height:10px", #readonly = "", #placeholder = "Type", #id = "Event_Type" } })
</div>
<div class="form-check-inline col-12" style="margin-top:1%">
<label class="control-label col-md-5" style="font-size:13px">Status</label>
#Html.EditorFor(model => model._EventsLines.FirstOrDefault().Event_Status, new { htmlAttributes = new { #class = "form-control col-md-7", #style = "font-size:13px, height:10px", #readonly = "", #placeholder = "Status", #id = "Event_Status" } })
</div>
<div class="form-check-inline col-12" style="margin-top:1%">
<label class="control-label col-md-5" style="font-size:13px">Total Due</label>
#Html.EditorFor(model => model._EventsLines.FirstOrDefault().Event_TotalDue, new { htmlAttributes = new { #class = "form-control col-md-7", #style = "font-size:13px, height:10px", #readonly = "", #placeholder = "Total Due", #id = "Event_TotalDue" } })
</div>
</div>
}
<div class="col-12">
<div class="card border-primary" style="margin-top:5%; margin-left:-4%; width:113%">
<div class="card-header"> <h6>Sub-Events</h6></div>
<div class="card-body">
<table id="SubEventsDatatables" class="display col-12">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Start Date</th>
<th scope="col">Status</th>
<th scope="col">Fees</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#section Scripts{
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script type="text/javascript">
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
//btn.onclick = function () {
// modal.style.display = "block";
//}
// When the user clicks on <span> (x), close the modal
span.onclick = function () {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
////triggered when modal is about to be shown
//$('#myModal').on('show.bs.modal', function (e) {
// GetEventsDetails();
// //get data-id attribute of the clicked element
// var id = $(this).data('id');
// //populate the textbox
// $(e.currentTarget).find('input[name="Event_StartDate"]').val('id');
//});
//once the modal has been shown
$('#myModal').on('shown.bs.modal', function () {
//Get the datatable which has previously been initialized
var dataTable = GetEventsDetails();
//recalculate the dimensions
dataTable.columns.adjust().responsive.recalc();
//get data-id attribute of the clicked element
var id = $(this).data('id');
//populate the textbox
$(e.currentTarget).find('input[name="Event_StartDate"]').val('id');
});
$(document).ready(function () {
});
//$(function () {
// $(".myModal").click(function () {
// var my_id = $(this).data('id');
// $(".modal-body #hiddenValue").val(my_id);
// })
//});
function GetEventsDetails() {
return $('#SubEventsDatatables').DataTable({
"paging": false,
"ordering": false,
"searching": false,
"info": false,
processing: true,
ajax: {
"url": '#Url.Action("GetEventsDetails", "Events")' + "/" + 1053 + "/" + 1454,
"type": "GET",
"datatype": "json",
succes: function (data) {
$("#Name").val(data['Name_cU']);
$("#Name").val(data['Date']);
$("#Name").val(data['Status']);
$("#Name").val(data['Fee_cU']);
},
},
columns: [
{ "data": "Name_cU" },
{ "data": "Date" },
{ "data": "Status" },
{ "data": "Fee_cU" },
]
});
}
</script>
}
Based on your last comment, you would just need to change your EventViewModel to something like this (although it sounds like you've already done this):
public class EventViewModel
{
public List<Events> _Events { get; set; }
public List<SubEvents> _SubEvents { get; set; }
}
Then, in your view, you can just do something like this (but obviously using the properties of an _Events type):
<table>
<thead>
<tr>
<td>Name</td>
<td>Start Date</td>
</tr>
</thead>
<tbody>
#foreach(var item in Model._Events)
{
<tr>
<td>#item.Name</td>
<td>#item.StartDate</td>
</tr>
}
</tbody>
</table>
EDIT
I would suggest something like this then. Build the table like I showed before (updated to match your model as best I can). Use a button with the "data-" attribute that contains some identifier for that Event. Use javascript to handle the click of the button and call a method on your controller that will get the subevents for the selected event (even return a partial view). In the success function, populate the html of the modal with the subevents and display the modal. When you say "datatables", are you referring to datatables.net?
<table id="example" class="table table-hover" style="width:100%; margin-top:2%">
<thead>
<tr>
<th></th>
<th scope="col">Event Name</th>
<th scope="col">Start Date</th>
<th scope="col">End Date</th>
<th scope="col">City</th>
<th scope="col">Country</th>
<th scope="col">Type</th>
<th scope="col">Status</th>
<th scope="col">Total Due</th>
</tr>
</thead>
<tbody>
#foreach(var item in Model._Events)
{
<tr>
<td><button data-id="#item.Id">View Details</button></td>
<td>#item.Event_Name</td>
<td>#item.Event_DateStart</td>
<td>#item.Event_DateEnd</td>
<td>#item.Event_City</td>
<td>#item.Event_Country</td>
<td>#item.Event_Type</td>
<td>#item.Event_Status</td>
<td>#item.Event_TotalDue</td>
</tr>
}
</tbody>
</table>
You're probably better off posting a new question(s) to accomplish the rest of your goals. Hopefully, this will get you going in the right direction.
I have a scenario where in I need to store multiple rows in a single table.Let me explain it in detail.
I have a table Price which has 4 columns, ID, ModelID, AppSettingID,Amount.
I am looking for inserting multiple values to the table where
ID would be the Primary Key.
ModelID would be same for all the rows.
AppSettingID and Amount will be different for all the rows and would be based on the selection user does on the view.
I have bound the AppSettingID to different combo boxes on the view as I have it categorized in the database.
This is what I am doing right now.
View:
<div class="editor-label">
#Html.LabelFor(model => model.ModelID, "Model")
</div>
<div class="editor-field">
#Html.DropDownList("ModelID", String.Empty)
#Html.ValidationMessageFor(model => model.ModelID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AppsettingID, "Mobile Condition")
</div>
<div class="editor-field">
#Html.DropDownList("Mobile Condition", new SelectList(ViewBag.ConditionID, "Text", "Value"))
#Html.ValidationMessageFor(model => model.AppsettingID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Amount)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Amount)
#Html.ValidationMessageFor(model => model.Amount)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AppsettingID, "Tennure")
</div>
<div class="editor-field">
#Html.DropDownList("Tennure", new SelectList(ViewBag.AppsettingID, "TexT", "Value"))
#Html.ValidationMessageFor(model => model.AppsettingID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Amount)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Amount)
#Html.ValidationMessageFor(model => model.Amount)
</div>
<p>
<input type="submit" value="Create" />
</p>
Controller:
public ActionResult Create()
{
//ViewBag.AppsettingID = db.Appsettings.Select(r => r.ID).Distinct();
ViewBag.ModelID = new SelectList(db.Models, "ID", "Name");
//ViewBag.Tennure = db.Appsettings.Select(s => s.Type == "Tennure").Distinct();
IQueryable<Appsetting>TennureIDs = db.Appsettings.Where(s => s.Type == "Tennure").Distinct();
IQueryable<Appsetting> Conditions = db.Appsettings.Where(s => s.Type == "Mobile Condition").Distinct();
List<SelectListItem> items = new List<SelectListItem>();
foreach (var t in TennureIDs)
{
SelectListItem s = new SelectListItem();
s.Text = t.ID.ToString();
s.Value = t.Value.ToString();
items.Add(s);
}
ViewBag.AppsettingID = items;
List<SelectListItem> conds = new List<SelectListItem>();
foreach (var t in Conditions)
{
SelectListItem s = new SelectListItem();
s.Text = t.ID.ToString();
s.Value = t.Value.ToString();
conds.Add(s);
}
ViewBag.ConditionID = conds;
return View();
}
//
// POST: /Price/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Price price, FormCollection form)
{
if (ModelState.IsValid)
{
int test = Convert.ToInt16(form["Mobile Condition"]);
price.AppsettingID = test;
db.Prices.Add(price);
db.SaveChanges();
return RedirectToAction("Index");
}
//ViewBag.AppsettingID = new SelectList(db.Appsettings, "ID", "Type", price.AppsettingID);
//ViewBag.ModelID = new SelectList(db.Models, "ID", "Name", price.ModelID);
return View(price);
}
I hope this solution will help you
The following is a razor page, here I have displayed the model in table format
#model List<MyModel>
<h2>Create</h2>
#using (Html.BeginForm())
{
<table>
<tr>
<th>
Model ID
</th>
<th>
App Setting ID
</th>
<th>
Amount
</th>
</tr>
#for (int i = 0; i < Model.Count; i++)
{
<tr>
<td>
#Html.TextBoxFor(x => Model[i].ModelID)
</td>
<td>
#Html.TextBoxFor(x => Model[i].AppsettingID)
</td>
<td>
#Html.TextBoxFor(x => Model[i].Amount)
</td>
</tr>
}
</table>
<input type="submit" />
}
When user clicks the submit button, it will pass the model to the controller
Controller
[HttpPost]
public ActionResult Create(List<MyModel> m)
{
// Do Coding
return View("Create", m);
}
I have 3 views (1 Index, 2 Contacts(partialview), 3 Details(partialview))
I have a database with 2 tables tied by ContactId that i can use to get the Details from the database to show. I used ADO to make a model of the database. The 2 tables (classes) are named Contact and ContactTelefon.
Instead of button I tried using #html.ActionLink (as u can see in Contact View) to get the Id from the row, but that takes me to a new page, and it doesn't even show details.
My question is: How could i get the details to show in textboxes so i can edit the data.
All actions must be in same view as far as the user is concerned.
Controller:
ContactsDbEntities db = new ContactsDbEntities();
[HttpGet] //Index
public ActionResult Index()
{
return View();
}
//Contacts
public ViewResult Contacts()
{
var contactsList = db.Contacts.ToList();
return View(contactsList);
}
//Details
public ActionResult Details(int? id)
{
ContactTelefon contactTel = db.ContactTelefons.Find(id);
return View(contactTel);
}
Index view
#using Demo.Models
#model Contact
#section scripts
{
<link href="~/Content/jquery-ui.min.css" rel="stylesheet" />
<script src="~/Scripts/jquery-ui.min.js"></script>
<script src="~/Scripts/jquery-ui.js"></script>
<script>
$(function () {
$(document).on('click', '#Details', function () {
$.get('#Url.Action("Details","Home")', function (data) {
$('#divDetails').replaceWith(data);
});
});
</script>
}
<table id="mainTable" class="table table-bordered table-striped">
<tr>
<th>
#Html.DisplayNameFor(model => model.ContactId)
</th>
<th>
#Html.DisplayNameFor(model => model.Nume)
</th>
<th>
#Html.DisplayNameFor(model => model.Prenume)
</th>
<th>
#Html.DisplayNameFor(model => model.Adresa)
</th>
<th>
#Html.DisplayNameFor(model => model.Mentiuni)
</th>
</tr>
<tr>
<th>
</th>
#using (Html.BeginForm())
{
<th>
#Html.TextBoxFor(model => model.Nume, null, new { id = "txtSearchNume", #class = "form-control" })
</th>
<th>
#Html.TextBoxFor(model => model.Prenume, null, new { id = "txtSearchPrenume", #class = "form-control" })
</th>
<th>
#Html.TextBoxFor(model => model.Adresa, null, new { id = "txtSearchAdresa", #class = "form-control" })
</th>
<th>
#Html.TextBoxFor(model => model.Mentiuni, null, new { id = "txtSearchMentiuni", #class = "form-control" })
</th>
<th>
<input type="submit" value="Create" class="btn btn-success"
onclick=" location.href='#Url.Action("Index", "Home")' " />
</th>
<th>
<input type="submit" name="submitSearch" value="Search" class="btn btn-info"
onclick=" location.href='#Url.Action("Create", "Home")' " />
</th>
<tr>
#{Html.RenderAction("Contacts", "Home");}
</tr>
<tr><div id="divDetails"></div></tr>
}
</table>
Contacts View
#using Demo.Models
#model IEnumerable<Contact>
<table class="table table-bordered table-hover">
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ContactId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Nume)
</td>
<td>
#Html.DisplayFor(modelItem => item.Prenume)
</td>
<td>
#Html.DisplayFor(modelItem => item.Adresa)
</td>
<td>
#Html.DisplayFor(modelItem => item.Mentiuni)
</td>
<td>
#Html.ActionLink("Delete", "Delete", new { id = item.ContactId },
new { #class = "btn btn-danger", onclick = "return confirm('Delete this record?');" })
</td>
<td>
<input id="Details" type="button" name="Details"
value="Details" class="btn btn-info" />
</td>
<td>
#Html.ActionLink("DetailsLink","Details",new{id = item.ContactId})
</td>
</tr>
}
</table>
Details View
#using Demo.Models
#model ContactTelefon
<div class="form-horizontal">
<div claass="form-group">
#* must get the id from Contacts *#
#Html.LabelFor(model => model.ContactId)
#Html.LabelFor(model => model.ContactTelefonId)
#Html.LabelFor(model => model.NumarTelefon)
#Html.LabelFor(model => model.TipNumarTelefon)
</div>
<br />
<div claass="form-group">
#Html.DisplayFor(model => model.ContactId)
#Html.DisplayFor(model => model.ContactTelefonId)
#Html.DisplayFor(model => model.NumarTelefon)
#Html.DisplayFor(model => model.TipNumarTelefon)
</div>
<div claass="form-group">
#Html.EditorFor(model => model.ContactId)
#Html.EditorFor(model => model.ContactTelefonId)
#Html.EditorFor(model => model.NumarTelefon)
#Html.EditorFor(model => model.TipNumarTelefon)
</div>
</div>
It seems as if you're starting MVC coming from ASP.NET WebForms. The thing about MVC is that it doesn't do any magic like WebForms so you have to have a good understanding of what happens behind the scenes to be able to make a smooth transition. Also, from the looks of it your database model uses Entity Framework.
First off the way you're handling the Details button is all wrong. What you should be doing is this:
HTML
<input type="button" name="Details" value="Details" class="btn btn-info js-details"
data-id="#item.ContactId" />
JavaScript
$(document).on('click', '.js-details', function (event) {
// get the element that triggered the event
var $element = $(event.currentTarget);
var id = $element.data('id');
// you might have to type in the literal URL if you have a custom route
// here
$.get('#Url.Action("Details","Home")'+ '?id=' + id, function (data) {
$('#divDetails').html(data);
});
});
Let me know if this works for you. There are other things that you can improve but this should be a pretty good start.
I have form which contains some text filed for filling data. I want to fill data in text box after dropdownlist changed.
MyView.chstml
#model BloodBank.Models.NewCamp
#{
ViewBag.Title = "New Camp";
Layout = "~/Views/Shared/_Layout - Menu.cshtml";
}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("select#OrganisationID").change(function (evt) {
if ($("select#OrganisationID").val() != "0") {
$.ajax({
url: "GetOrganizationInfo?orgID=" + $("select#OrganisationID").val(),
type: 'POST',
data: { OS: $("select#OrganisationID").val() },
success: function (response) {
$("select#OrganisationID").replaceWith(response)
},
error: function (xhr) {
alert("Something went wrong, please try again");
}
});
}
});
});
</script>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true, "New Camp creation was unsuccessful. Please correct the errors and try again.")
<div>
<table style="border-style:none;border-width:0;border:0;">
<tbody>
<tr>
<td style="border:0;vertical-align:middle;">
<div class="editor-label">
#Html.LabelFor(m => m.OrganisationID)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.DropDownListFor(m => m.OrganisationID, (SelectList)ViewBag.OrganisationList)
#* <select id="Area">
#foreach (var arearow in (SelectList)ViewBag.OrganisationList)
{
<option value="#arearow.Value">#arearow.Text</option>
}
</select>*#
#Html.ActionLink("Add New Organisation", "AddOrganisation", "Organisation", null, null)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.ValidationMessageFor(m => m.OrganisationID)
</div>
</td>
</tr>
<tr>
<td style="border:0;text-align:left;" colspan="2"> <h3>Contact Person Information</h3></td>
</tr>
<tr>
<td style="border:0;">
<div class="editor-label">
#Html.LabelFor(m => m.Email)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.TextBoxFor(m => m.Email)
#Html.ValidationMessageFor(m => m.Email)
</div>
</td>
</tr>
<tr>
<td style="border:0;">
<div class="editor-label">
#Html.LabelFor(m => m.FirstName)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.TextBoxFor(m => m.FirstName)
#Html.ValidationMessageFor(m => m.FirstName)
</div>
</td>
</tr>
<tr>
<td style="border:0;">
<div class="editor-label">
#Html.LabelFor(m => m.LastName)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.TextBoxFor(m => m.LastName)
#Html.ValidationMessageFor(m => m.LastName)
</div>
</td>
</tr>
<tr>
<td style="border:0;">
<div class="editor-label">
#Html.LabelFor(m => m.Phone)
</div>
</td>
<td style="border:0;">
<div class="editor-field">
#Html.TextBoxFor(m => m.Phone)
#Html.ValidationMessageFor(m => m.Phone)
</div>
</td>
</tr>
<tr>
<td colspan="2" style="border:0;text-align:center;">
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit" id="ClickMe" class="cssLoginButton blue"/>
</div>
}
My Action
[Authorize]
[OutputCache(Location = OutputCacheLocation.None)]
public ActionResult NewCamp()
{
var user = (BloodBank.Security.BloodBankMembershipUser)Membership.GetUser();
this.BindOrganisations(user.BloodBankID);
return View();
}
public ActionResult GetOrganizationInfo(string orgID)
{
if (!string.IsNullOrEmpty(orgID))
{
var model = (new UserManager()).GetCampPersonOrganisationDetailsByOrganisationID(orgID);
Models.NewCamp newcampModel = new Models.NewCamp();
if (model.Count > 0)
{
newcampModel.CampID = model[0].CampID;
newcampModel.Organisation = "";
newcampModel.OrganisationID = model[0].OrganisationID;
newcampModel.FirstName = model[0].FirstName;
newcampModel.LastName = model[0].LastName;
newcampModel.Email = model[0].Email;
newcampModel.Phone = model[0].Phone;
var organisations = this.GetOrganisations(model[0].BloodBankID);
if (organisations != null)
ViewBag.OrganisationList = new SelectList(organisations, "OrganisationID", "NameCity");
}
return View("NewCamp", newcampModel);
}
else
return View();
}
I am not able to fill data in the form. I am not getting why I am not able to fill data. Is there any change in script or in my code? Is there any example to fill data after dropdownlist value changed?
--------- Update------------
I have tried similar thing on a sample project. Here I can fetch the values and display in text box, but I get one more view added on same View every time I choose OS from dropdown as in below screenshot.
the only flaw in the code you posted might be a missing ;
success: function (response) {
$("select#OrganisationID").replaceWith(response);
},
Hello Everyone I have solved my problem using this. There is no need to create any javascript. I have solved this without using javascript.
#Html.DropDownListFor(m => m.OrganisationID, (SelectList)ViewBag.OrganisationList, new { onchange = "document.location.href = 'NewCamp?orgID=' + this.options[this.selectedIndex].value;" })