mvc3 partial views for search, validate, submit final results - asp.net-mvc-3

I am creating a UI using MVC3 to generate a text file message based on user selections. User needs to find a patient by ID, then a provider by name from my db, and then initiate the creation of the text file. I have the message generator working if the right objects are passed to it (separate assembly).
I need some help understanding how to implement the search/select/clear logic, and the submission of results to call the generator. (New to MVC3).
I made partial views to display the search results, and I have the basic search results showing up on my Index view.
Issues:
My provider search returns a list of providers by last name & first name, and I need my user to select one, if there are more than one by the name.
How do I put these partial views inside a third, to send their results?
How can I make it possible to clear results in the partials? How do I make sure that I have a valid value in the partials before I send the result?
Any direction would be helpful. Thanks.
Here's my HomeController:
public class HomeController : Controller
{
private CrdDatabase db = new CrdDatabase(ConfigurationManager.ConnectionStrings["connectionString_CRD_TEST"].ConnectionString);
public PartialViewResult PatientSearch(string clinicNumber)
{
var patient = db.GetCRDPatientInformation(clinicNumber);
if (patient != null)
{
return PartialView("_PatientSearchResult", patient);
}
// need to determine how to return an error message/validation message.
return PartialView("_PartialClear");
}
public PartialViewResult ProviderSearch(string lastName, string firstname)
{
var providerList = db.GetCRDProviderList(lastName, firstname);
if (providerList.Count < 1)
{
return PartialView("_ProviderSearchResults", providerList);
}
return PartialView("_PartialClear");
}
public ActionResult Index()
{
return View();
}
}
Here is the _PatientSearchResult.cshtml partial view:
#model Objects.CRDPatientInfo
<table id="searchResults">
<tr>
<th>
Clinic Number
</th>
<th>
Last Name
</th>
<th>
First Name
</th>
<th>
Middle Name
</th>
<th>
Date of Birth
</th>
<th>
Admin Gender
</th>
</tr>
<tr>
<td>
#Model.clinic_number
</td>
<td>
#Model.pat_name_last
</td>
<td>
#Model.pat_name_first
</td>
<td>
#Model.pat_name_mid
</td>
<td>
#Model.pat_birth_date
</td>
<td>
#Model.pat_gender_code
</td>
</tr>
</table>
The _ProviderSearchResults.cshtml is similar, except it loops through the list in the model.
Here is my Index.cshtml, so far:
#{
ViewBag.Title = "Muse Orders Home Page";
}
<h2>#ViewBag.Message</h2>
#using (Ajax.BeginForm("PatientSearch", "Home", new AjaxOptions
{
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "searchPatientResults"
}))
{
<text>Clinic Number:</text>
<input type="text" name="clinicNumber" />
<input type="submit" name="submitButton" value="Search" />
<input type="submit" name="submitButton" value="Clear" />
}
<table id="searchPatientResults">
</table>
#using (Ajax.BeginForm("ProviderSearch", "Home", new AjaxOptions{
HttpMethod = "GET",
InsertionMode= InsertionMode.Replace,
UpdateTargetId= "searchProviderResults"
}))
{
<text>Provider Last Name:</text>
<input type="text" name="lastName" />
<text>Provider First Name:</text>
<input type="text" name="firstName" />
<input type="submit" name="submitButton" value="Search" />
<input type="submit" name="submitButton" value="Clear" />
}
<table id="searchProviderResults">
</table>
#using (Ajax.BeginForm("GenerateOrder", "Home", new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "generateOrder"
}))
{
<input type="hidden" name="patient" />
<input type="hidden" name="provider" />
<input type="submit" name="submitButton" value="GenerateOrder" />
<input type="submit" name="submitButton" value="Clear" />
}
<table id="generateOrder">
</table>

Related

Adding new item to database using ASP.NET Core MVC

I'm building a Pet Shop website using ASP.NET Core MVC (the latest version).
I have database with instructions for primary key and identity(1,1) (auto increment).
In my website,in order to check and see if my 'Create' method is working, I've created a page (a controller and view) of Create new animal and a page for the list of all the animals that I've got (Index controller). After clicking Submit on the create page, it's redirected to Index - where I should see the animal that I've added (this line wrote on SQL):
The problem is that I don't see anything added to my list (the photo above). After a few tries, I've tried to add animal directly in my SQL and I saw that it's got the number ID 22 - meaning that maybe I did succeeded to add new animal and I just don't see it?
I really don't know where my problem is and I would be happy to get help.
Controller:
public async Task<IActionResult> Index()
{
var petShopDataContext = _context.Animals.Include(a => a.Category);
return View(await petShopDataContext.ToListAsync());
}
public async Task<IActionResult> CreateAnimal()
{
var categories = await _categoryService.GetAnimalCategory();
ViewBag.Categories = categories.Select(c => new SelectListItem(c.Name, c.CategoryId.ToString())).ToList();
return View();
}
public async Task<IActionResult> CreateAnimal([FromForm] CreateAnimalViewModel vm)
{
vm.Animal.Category = await _categoryService.GetAsync(vm.Animal.CategoryId);
_animalService.AddAnimalAsync(vm.Animal, vm.Photo);
return RedirectToAction("Index");
}
CreateAnimalViewModel:
public class CreateAnimalViewModel
{
public Animal Animal { get; set; }
public IFormFile Photo { get; set; }
}
Create Animal View:
#model PetShop.Client.Models.CreateAnimalViewModel
#{
ViewBag.Title = "CreateAnimal";
}
<h4>Create New Animal</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="CreateAnimal" enctype="multipart/form-data" method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Animal.Name" class="control-label"></label>
<input asp-for="Animal.Name" class="form-control" />
<span asp-validation-for="Animal.Name" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Animal.BirthDate" class="control-label"></label>
<input asp-for="Animal.BirthDate" class="form-control" />
<span asp-validation-for="Animal.BirthDate" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Animal.Description" class="control-label"></label>
<input asp-for="Animal.Description" class="form-control" />
<span asp-validation-for="Animal.Description" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Animal.Category">Category</label>
<select asp-for="Animal.CategoryId" asp-items="ViewBag.Categories" class ="form-control" id="category"></select>
<span asp-validation-for="Animal.CategoryId" />
<a asp-controller="Admin" asp-action="CreateCategory">
<input type="button" value="Add new category"/>
</a>
</div>
<div class="form-group">
<label asp-for="Photo" class="control-label"></label>
<input type="file" asp-for="Photo" accept="image/*" class="form-control-file"/>
<span asp-validation-for="Photo" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
Index View:
#model IEnumerable<PetShop.Data.Models.Animal>
#{
ViewBag.Title = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="CreateAnimal">Create New</a>
</p>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.BirthDate)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.PhotoUrl)
</th>
<th>
#Html.DisplayNameFor(model => model.Category)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.BirthDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.PhotoUrl)
</td>
<td>
#Html.DisplayFor(modelItem => item.Category.Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.AnimalId">Edit</a> |
<a asp-action="Details" asp-route-id="#item.AnimalId">Details</a> |
<a asp-action="Delete" asp-route-id="#item.AnimalId">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Animal Service:
public async Task<Animal> AddAnimalAsync(Animal animal, IFormFile image)
{
var entity = _animalRepository.Add(animal);
var path = await _imageService.UploadImage(image, animal);
if (path != String.Empty)
{
return _animalRepository.Update(entity);
}
return entity;
}
Animal Repository:
public Animal Add(Animal entity)
{
_context.Animals.Add(entity);
_context.SaveChanges();
return entity;
}

Change Data in DataTable with Select from Dropdownlist

I have a view with a Datatable, and I want to change the data every time I select a category from a drop-down list.
I want to only display the albums from the selected category, or all albums from all categories, using Ajax and jQuery. The drop-down list must be placed above the table.
Here is my code:
#using System.Collections.Generic;
#using CakeStore.App.Areas.Admin.Models.Albums;
#using CakeStore.App.Services.Contracts;
#addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
#inject IAlbumService AlbumService
#{ ViewData["Title"] = "Category Albums";
Layout = "~/Areas/Admin/Views/Shared/_AdminLayout.cshtml";
var albums = ViewBag.CategoryAlbums as List<AlbumTableViewModel>;
}
<h1 class="text-center text-header-page">Category Albums</h1>
<hr class="hr-admin-divider" />
<div class="form-group">
<a class="btn button-black-white d-flex justify-content-left" href="/Admin/Albums/Create">Create</a>
</div>
<hr class="hr-admin-divider" />
<div class="d-flex">
<table class="table table-striped table-hover" id="myTable">
<tr>
<th>#</th>
<th>Name</th>
<th>Category</th>
<th></th>
<th></th>
<th></th>
</tr>
#for (int i = 0; i < albums.Count(); i++) {
<tr>
<td class="col-md-1">#albums[i].Id</td>
<td class="col-md-3">#albums[i].Name</td>
<td class="col-md-2">#albums[i].Category</td>
<td><a class="btn button-table-edit" href="/Admin/Albums/Edit?id=#albums[i].Id">EDIT</a></td>
<td><a class="btn button-table-delete d-flex justify-content-right" href="/Admin/Albums/Delete?id=#albums[i].Id">DELETE</a></td>
<td><a class="btn button-table-view d-flex justify-content-right" href="/Admin/Products/CategoryAlbums?id=#albums[i].Id">PRODUCTS</a></td>
</tr>
}
</table>
</div>
<div class="row d-flex align-items-end flex-column" style="font-size:12px">
<a class="btn-link pull-right col-lg-2" asp-controller="Categories" asp-action="Category">Back to Categories</a>
</div>
#section Scripts {
<partial name="_ValidationScriptsPartial" />
}
You could use the Partial View ,I made the demo ,you could refer to it
Use ajax to call the GetCityList method to get the data corresponding to the countryId passed .
<div class="form-group">
<label class="col-form-label">Country</label>
<select class="form-control" asp-items="#ViewBag.Country" id="selectlist">
<option>All</option>
</select>
</div>
<div class="form-group" id="cityListWrapper">
<partial name="_CityListPartial" model="#ViewBag.City" />
</div>
#section Scripts
{
<script type="text/javascript">
$("#selectlist").change(function () {
var countryId = $("#selectlist").val();
$.ajax
({
type: "GET",
url: "/Countries/GetCityList?CountryId="+countryId,
success: function (result) {
$("#cityListWrapper").html(result)
}
});
});
</script>
}
Initial rendering the main view , show all albums when not selected
public async Task<IActionResult> Index()
{
ViewBag.Country = new SelectList(_context.Country, "Id", "CountryName");
ViewBag.City = _context.City.ToList();
return View();
}
The GetCityList action ,render the partial view using a statement that returns different values
[HttpGet]
public async Task<IActionResult> GetCityList(int? countryId)
{
if (countryId == null)
{
var CityList = await _context.City.ToListAsync();
return PartialView("_CityListPartial", CityList);
}
var Cities =await _context.City.Where(c => c.Country.Id == countryId).ToListAsync();
return PartialView("_CityListPartial", Cities);
}
How it works

asp.net mvc table does not update after filtering with checkboxes

I am doing the ticket application and I am making filtration of items with checkboxes. First the page loads every item in database and view displays it in the table. Then a user can click on the checkbox and view displays just the selected categories. It is supposed to be updated on the checkbox click.
Controller Action:
public ActionResult Display(int[] checkId)
{
if (checkId == null)
{
DispDisplayVM viewModel = new DispDisplayVM
{
Jidlos = db.Jidlos.ToList(),
//Jidlos = (from Jidlo jidlo in db.Jidlos where checkId.Contains(jidlo.CategoryID) select jidlo).ToList(),
Categories = db.Categories.ToList()
};
return View(viewModel);
}
else
{
DispDisplayVM viewModel = new DispDisplayVM
{
//Jidlos = db.Jidlos.ToList(),
Jidlos = (from Jidlo jidlo in db.Jidlos where checkId.Contains(jidlo.CategoryID) select jidlo).ToList(),
Categories = db.Categories.ToList()
};
return View(viewModel);
}
}
Data into controller are passed by ajax. It can be one value or an array. Then there is a LINQ query to filter database.
View:
#using jidloApp.Classes
#using jidloApp.Models
#model DispDisplayVM
#{
ViewBag.Title = "Display";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Display</h2>
<div class="container">
Pridat novy recept
</div>
<div class="btn-group" data-toggle="buttons">
<label class="form-check-label">
<input class="form-check-input" type="checkbox" value="1" name="checkId">
Kuřecí
</label>
<label class="form-check-label">
<input class="form-check-input" type="checkbox" value="2" name="checkId">
Vepřové
</label>
<label class="form-check-label">
<input class="form-check-input" type="checkbox" value="3" name="checkId">
Hovězí
</label>
<label class="form-check-label">
<input class="form-check-input" type="checkbox" value="4" name="checkId">
Krůtí
</label>
<label class="form-check-label">
<input class="form-check-input" type="checkbox" value="5" name="checkId">
Vegetariánské
</label>
</div>
<table class="table">
<thead>
<tr>
<th>Nazev Jidla</th>
<th>Kategorie</th>
<th>Akce</th>
</tr>
</thead>
<tbody>
#foreach (Jidlo jidlo in Model.Jidlos)
{
<tr>
<td>
#Html.DisplayFor(modelItem => jidlo.name)
</td>
<td>
#Html.DisplayFor(modelItem => jidlo.Category.popis)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = jidlo.JidloID }) |
#Html.ActionLink("Details", "Details", new { id = jidlo.JidloID }) |
#Html.ActionLink("Delete", "Delete", new { id = jidlo.JidloID })
</td>
</tr>
}
</tbody>
</table>
<script>
$(document).ready(function () {
$('input[name="checkId"]').click(function () {
getSelectedCheckBoxes();
});
var getSelectedCheckBoxes = function () {
var idArray = [];
$('input[name="checkId"]:checked').each(function () {
idArray.push($(this).attr("value"));
});
$.ajax({
url: '#Url.Action("Display", "Disp")',
type: "POST",
data: { checkId: idArray },
dataType: "json",
traditional: true,
success: function () {
alert("ajax request to server succeed");
}
});
};
});
</script>
Data filtering is working fine and requested data are passed into the view correctly.
What is not working is when I click on the checkbox, the table stays the same as before and does not update. I really can not find what is wrong here. Can you please give some advice what to do?
Btw the table updates when I create new item in database or I delete it...
I think you need a View and a PartialView.
Controller:
public ActionResult Index()
{
return View();
}
public PartialViewResult Display(int[] checkId)
{
DispDisplayVM viewModel = null;
[youre code]
return PartialView(viewModel)
}
Index View:
#{
ViewBag.Title = "Display";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Display</h2>
<div class="container">
Pridat novy recept
</div>
<div class="btn-group" data-toggle="buttons">
<label class="form-check-label">
<input class="form-check-input" type="checkbox" value="1" name="checkId">
Kuřecí
</label>
<label class="form-check-label">
<input class="form-check-input" type="checkbox" value="2" name="checkId">
Vepřové
</label>
<label class="form-check-label">
<input class="form-check-input" type="checkbox" value="3" name="checkId">
Hovězí
</label>
<label class="form-check-label">
<input class="form-check-input" type="checkbox" value="4" name="checkId">
Krůtí
</label>
<label class="form-check-label">
<input class="form-check-input" type="checkbox" value="5" name="checkId">
Vegetariánské
</label>
</div>
<div id="data-container"></div>
<script>
$('input[name="checkId"]').on("click",function () {
var idArray = [];
$("input[name="checkId"]:checked").each(function () {
idArray.push($(this).attr("value"));
});
$("#data-container").load("#Url.Action("Display", "Disp")",{ checkId: idArray });
});
</script>
Display View:
#using jidloApp.Classes
#using jidloApp.Models
#model DispDisplayVM
<table class="table">
<thead>
<tr>
<th>Nazev Jidla</th>
<th>Kategorie</th>
<th>Akce</th>
</tr>
</thead>
<tbody>
#foreach (Jidlo jidlo in Model.Jidlos)
{
<tr>
<td>
#Html.DisplayFor(modelItem => jidlo.name)
</td>
<td>
#Html.DisplayFor(modelItem => jidlo.Category.popis)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = jidlo.JidloID }) |
#Html.ActionLink("Details", "Details", new { id = jidlo.JidloID }) |
#Html.ActionLink("Delete", "Delete", new { id = jidlo.JidloID })
</td>
</tr>
}
</tbody>
</table>
Code written "on fly"

How to provide validation with single button in mvc3

I have two buttons on single form.
First button used to upload file and second button is submit .
I want validation , when i clicked on submit button that time validation should be generate.
But in my application when i clicked on upload button that time validation generated.
View:
<% using (Html.BeginForm("Create","Document", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
<table>
<tr>
<td >
File Name:
</td>
<td >
<%: Html.EditorFor(model=>model.document.DOCUMENT_NAME) %>
<%: Html.ValidationMessageFor(model => model.document.DOCUMENT_NAME) %>
</td>
</tr>
<tr>
<td>
Select File:
</td>
<td>
<input type="file" name="file" id="file" style="height: 24px" />
<input type="submit" name="submitButton" value="Upload" />
</td>
<tr>
</table>
<div>
<input type="submit" name="submitButton" value="Create" />
</div
<%}%>
Controller:
[Required]
[Display(Name = "DOCUMENT NAME")]
[ReadOnly(true)]
public string DOCUMENT_NAME
{
get;
set;
}
Any button on form (and You have two) will trigger validation. One of possibile solutions is replace upload button by some element and do uploading via jquery.
you can also check which button is click like below
View:
<div>
<input type="file" name="file" id="file" style="height: 24px" />
<input type="submit" id="btnUpload" name="submitButton" value="Upload" />
</div>
<div>
<input type="submit" id="btnCreate" name="submitButton" value="Create" />
</div
controller
public ActionResult actionName(string btnUpload,string btnCreate)
{
//now you can easily check here for which button is clicked
if(btnUpload != null || btnUpload !="")
{
//perform uploading logic here
}
if(btnCreate!=null || btnCreate !="")
{
//perform your validation here
}
}
i hope this will help you.

MVC3 razor How to repeatedly add Set of fields to my page on clicking a button?

How to repeatedly add Set of fields to my page on clicking a button?
I have a button "Add records" on my ParentView.cshtml
on Click of this "Add records" button ,I need the below mentioned razor view(childView.cshtml) to be appended on my ParentView.Each time I click of this "Add records" button ,I need new empty ChildView.cshtml to be appended to my Parent view.Can some one help me how can I achieve this functionality ?
ChildView.cshtml
<p>Record index
#Html.EditorFor(model => model.Name)
#Html.EditorFor(model => model.Address)
#Html.EditorFor(model => model.Location)
<input type="submit" id="btnSave" value="Save" />
My ParentView.cshtml will look like below
#model MyWebRole.ViewModels.MyViewModel
#{
ViewBag.Title = "Address Book";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
<fieldset>
<legend style="font-size: small;">Add Address records </legend>
<br />
<table>
<tr>
<td rowspan="5">
<img alt="" id="imageBox" src="" width="395" height="225" />
</td>
<td>
<span>Address Book </span>
<br />
</td>
<td>
#Html.EditorFor(model => model.REcordTitle)
#Html.ValidationMessageFor(model => model.REcordTitle)
</td>
</tr>
------------------------
------------------------
</table>
<div><input type="submit" id="btnAdd records" value="Add Records" /></div>
</fieldset>
}
You could use the built-in Ajax helpers?
#model MyWebRole.ViewModels.MyViewModel
#{
ViewBag.Title = "Address Book";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Ajax.BeginForm(new AjaxOptions() {
UpdateTargetId = "RecordSection",
InsertionMode = InsertionMode.InsertAfter,
}))
{
<fieldset>
<legend style="font-size: small;">Add Address records </legend>
<br />
<table>
<tr>
<td rowspan="5">
<img alt="" id="imageBox" src="" width="395" height="225" />
</td>
<td>
<span>Address Book </span>
<br />
</td>
<td>
#Html.EditorFor(model => model.REcordTitle)
#Html.ValidationMessageFor(model => model.REcordTitle)
</td>
</tr>
------------------------
------------------------
</table>
<div><input type="submit" id="btnAdd records" value="Add Records" /></div>
</fieldset>
}
<div id="RecordSection">
#* New Partial Views will be rendered here *#
</div>
Then in the Action which handles this you can use the Get/Post/Redirect design pattern to put a new PartialView on the Page:
[HttpPost]
public ActionResult AddressBook(MyViewModel model)
{
// do stuff with model, then pass an Id?
// to the Action which renders the partial view
return RedirectToAction("AddRecord", new { id = model.Id });
}
public ActionResult AddRecord(int id)
{
MyChildModel model = new MyChildModel();
model.Id = id;
return PartialView("_ChildView", model);
}
$('#btnAddRecords').click(function(){
$.getJSON("/MyController/AddRecord", null
function (data) {
$('#divToAddRecords').append(data);
});
})
In Controller:
public JsonResult AddRecord()
{
...
var res = SerializeControl("~/Views/Folder/ChildView.cshtml", viewModel);
return Json(res, JsonRequestBehavior.AllowGet);
}
private string SerializeControl()
{
var control = new RazorView(ControllerContext, controlPath, null, false, null);
ViewData.Model = model;
var writer = new HtmlTextWriter(new StringWriter());
control.Render(new ViewContext(ControllerContext, control, ViewData, TempData, writer), writer);
string value = writer.InnerWriter.ToString();
return value;
}
And change so that button that adds records does not submit

Resources