.NET Core 6 Pull Down Menu Selection to Group through View Model - asp.net-core-mvc

I am having partial success searching / grouping data through a viewmodel:
Partial Success:
URL Value
If I search on "B"
https://localhost:7207/Class01Name/Index2?String02NameSelected=B&SearchString=
Problem:
Not filtering data...simply changes pull down menu back to "All," displaying all data. Data not filtered.
**Question:
**
What in the code has to be changed to have the data filtered successfully?
Question is based on Tutorial at:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-6.0
Model
using System.ComponentModel.DataAnnotations; // Date Format
namespace Project01Name.Models
{
public class Class01Name
{
public int Id { get; set; }
public string? String01Name { get; set; }
public string? String02Name { get; set; }
public int? Int01Name { get; set; }
public bool? Bool01Name { get; set; }
[DataType(DataType.Date)]
public DateTime? DateTime01Name { get; set; }
}
}
**
View Model
**
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
namespace Project01Name.Models.ViewModelsName
{
public class SearchByGroupName
{
public List<Class01Name>? Class01NameList { get; set; } // A list of movies.
public SelectList? String02NameSelection { get; set; } // A SelectList containing the list of genres. This allows the user to select a genre from the list.
public string? String02NameSelected { get; set; } // MovieGenre, which contains the selected genre.
public string? SearchString { get; set; } // SearchString, which contains the text users enter in the search text box.
}
}
Controller Action Method
// GET: String01Names
public async Task<IActionResult> Index2(string class01NameGroup, string searchString)
{
// Use LINQ to get list of genres.
IQueryable<string> string02NameQuery = from m in _context.Class01Name
orderby m.String02Name
select m.String02Name;
var selectVariable = from m in _context.Class01Name
select m;
if (!string.IsNullOrEmpty(searchString))
{
selectVariable = selectVariable.Where(s => s.String01Name!.Contains(searchString));
}
if (!string.IsNullOrEmpty(class01NameGroup))
{
selectVariable = selectVariable.Where(x => x.String02Name == class01NameGroup);
}
var string02NameVM = new SearchByGroupName
{
String02NameSelection = new SelectList(await string02NameQuery.Distinct().ToListAsync()),
Class01NameList = await selectVariable.ToListAsync()
};
return View(string02NameVM);
}
View
#model Project01Name.Models.ViewModelsName.SearchByGroupName
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<form asp-action="Index2" method="get">
<div class="form-actions no-color">
<p>
<select asp-for="String02NameSelected" asp-items="Model.String02NameSelection"> <option value="">All</option></select>
Title: <input type="text" asp-for="SearchString" />
<input type="submit" value="Filter" />
#*<input type="submit" value="Search" class="btn btn-default" /> |
<a asp-action="Index">Back to Full List</a> *#
</p>
</div>
</form>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String02Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].Int01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].DateTime01Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Class01NameList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.String01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.String02Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Int01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateTime01Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Partial Success:
URL Value
If I search on "B"
https://localhost:7207/Class01Name/Index2?String02NameSelected=B&SearchString=
Problem:
Not filtering data...simply changes pull down menu back to "All," displaying all data. Data not filtered.
**Question:
**
What in the code has to be changed to have the data filtered successfully?
Question is based on Tutorial at:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-6.0

Not filtering data...simply changes pull down menu back to "All,"
displaying all data. Data not filtered.
**Question: ** What in the code has to be changed to have the data filtered successfully?
Well, seems you wanted to implement searching functionality in way, so that you can filter with the dropdown and search box and finally if you select All as dropdown value you want to load all the list without any filter and shorting means the full list which comes at first view.
If so, you need to use javascript for your dropdown change event as cshtml doesn't deal with change event. In addition, as you are using asp.net core MVC which would return HTML View altough, we need json data for Ajax reponse but we are would bee getting HTML View. So Ajax success Function will through an error where we would use filter with All parameter.
Modification Required:
Javascript:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("#allId").change(function () {
alert("Click");
var allId = $('#allId').val();
console.log(allId);
if (allId == "All") {
alert("Alert");
$.ajax({
url: 'http://localhost:5094/Search/Index2',
type: 'GET',
dataType: 'json',
data: { String02NameSelected: "All", searchString: "" },
success: function (response) {
},
error: function () {
window.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";
}
});
}
});
});
</script>
}
Note:
As you can see, in success function we are doing nothing, because it will always throuh an error because we are not returning json. Thus, we will work in error section. indow.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";. Here, for your understanding, we will call this function when we select All as our dropdown value in that scenario, we will pass All and nothing , nothing will convert into null and all will be our search key.
Modify Your Existing View:
In your existing view, replace blow dropdown code snippet , means the select items
<select asp-for="String02NameSelected" id="allId" asp-items="Model.String02NameSelection"> <option value="All">All</option></select>
Note: If you notice I hav introduced a id id="allId" which will be using on dropdown change event.
Controller:
public async Task<IActionResult> Index2(string String02NameSelected, string searchString)
{
if (String02NameSelected == "All" && searchString == null)
{
var dataWithoutfileter = new SearchByGroupName();
dataWithoutfileter.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
dataWithoutfileter.Class01NameList = listOfClass01Name;
return View(dataWithoutfileter);
}
if (!String.IsNullOrEmpty(String02NameSelected) && String02NameSelected !="All")
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(String02NameSelected.ToLower()) || m.String02Name.ToLower().Contains(String02NameSelected.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
if (!String.IsNullOrEmpty(searchString))
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(searchString.ToLower()) || m.String02Name.ToLower().Contains(searchString.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
//First loading
var objSearchByGroupName = new SearchByGroupName();
objSearchByGroupName.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
objSearchByGroupName.Class01NameList = listOfClass01Name;
return View(objSearchByGroupName);
}
}
Complete Demo:
Full Controller With Seed Model Class Value:
public class SearchController : Controller
{
public static List<Class01Name> listOfClass01Name = new List<Class01Name>()
{
new Class01Name() { Id =101, String01Name ="Titanic",String02Name = "Romantic", Int01Name =01, Bool01Name = false, DateTime01Name = new DateTime(2023-01-15) },
new Class01Name() { Id =102, String01Name ="Forest gump",String02Name = "Motivational", Int01Name =02, Bool01Name = true, DateTime01Name = new DateTime(2023-01-12) },
new Class01Name() { Id =103, String01Name ="Spider Man",String02Name = "Action", Int01Name =03, Bool01Name = false, DateTime01Name = new DateTime(2023-01-10) },
new Class01Name() { Id =104, String01Name ="Harry Potter",String02Name = "Suspense", Int01Name =04, Bool01Name = true, DateTime01Name = new DateTime(2023-01-13)},
};
public List<SelectListItem> String02NameSelectionList = new List<SelectListItem>()
{
new SelectListItem { Text = "Motivational", Value = "Motivational" },
new SelectListItem { Text = "Romantic", Value = "Romantic" },
new SelectListItem { Text = "Action", Value = "Action" },
new SelectListItem { Text = "Comedy", Value = "Comedy" }
};
public async Task<IActionResult> Index2(string String02NameSelected, string searchString)
{
if (String02NameSelected == "All" && searchString == null)
{
var dataWithoutfileter = new SearchByGroupName();
dataWithoutfileter.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
dataWithoutfileter.Class01NameList = listOfClass01Name;
return View(dataWithoutfileter);
}
if (!String.IsNullOrEmpty(String02NameSelected) && String02NameSelected !="All")
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(String02NameSelected.ToLower()) || m.String02Name.ToLower().Contains(String02NameSelected.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
if (!String.IsNullOrEmpty(searchString))
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(searchString.ToLower()) || m.String02Name.ToLower().Contains(searchString.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
//First loading
var objSearchByGroupName = new SearchByGroupName();
objSearchByGroupName.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
objSearchByGroupName.Class01NameList = listOfClass01Name;
return View(objSearchByGroupName);
}
}
Full View:
#model DotNet6MVCWebApp.Controllers.SearchByGroupName
#{
ViewData["Title"] = "Index";
}
<form asp-action="Index2" method="get">
<div class="form-actions no-color">
<p>
<select asp-for="String02NameSelected" id="allId" asp-items="Model.String02NameSelection"> <option value="All">All</option></select>
Title: <input type="text" asp-for="SearchString" />
<input type="submit" name="searchString" />
</p>
</div>
</form>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String02Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].Int01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].DateTime01Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Class01NameList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.String01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.String02Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Int01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateTime01Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("#allId").change(function () {
alert("Click");
var allId = $('#allId').val();
console.log(allId);
if (allId == "All") {
alert("Alert");
$.ajax({
url: 'http://localhost:5094/Search/Index2',
type: 'GET',
dataType: 'json',
data: { String02NameSelected: "All", searchString: "" },
success: function (response) {
},
error: function () {
window.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";
}
});
}
});
});
</script>
}
Output:

Related

Net Core- add data to different model

I am pulling the extra materials on the order page in my project. Since the model on this page is product, I need to run a cart class to add to cart. But I don't know how to do this with asp-for. How can I add data for class cart because the model on the page is product?
#if (product.ProductExtras.Any())
{
<h5>Ekstra Malzemeler</h5>
<ul class="clearfix">
#foreach (var extra in product.ProductExtras)
{
<li>
<label class="container_check">
#extra.Extra.Name<span>+ #extra.Extra.Price.ToString("c2")</span>
<input type="checkbox">
<span class="checkmark"></span>
</label>
</li>
}
</ul>
}
Include your cart class and product class in a single class, and use this class in the view, you can access the data of both the cart class and the product class.
Like this:
public class ViewModel
{
//Choose the data type depending on your needs
public List<cart> cart { get; set; }
public List<product> product { get; set; }
}
For more details you can refer to this link.
Update:
I try to send a post request with the state of the checkbox, maybe that's what you mean.
Controller:
[HttpGet]
public IActionResult Test()
{
ViewModel viewmodel = new ViewModel();
viewmodel.product = new List<Product>();
viewmodel.product.Add(new Product() {Id =1,Name="Product1" });
viewmodel.product.Add(new Product() { Id = 2, Name = "Product2" });
viewmodel.product.Add(new Product() { Id = 3, Name = "Product3" });
return View(viewmodel);
}
[HttpPost]
public JsonResult Test([FromBody]ViewModel viewmodel)
{
//your own processing logic
return Json(viewmodel);
}
View:
#model _2022080202.Models.ViewModel
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.product[0].Id)
</th>
<th>
#Html.DisplayNameFor(model => model.product[0].Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.product) {
<tr>
<td name = "Id">#Html.DisplayFor(modelItem => item.Id)</td>
<td name = "Name">#Html.DisplayFor(modelItem => item.Name)</td>
<td><input type="checkbox" value="#item.Id" /></td>
</tr>
}
</tbody>
</table>
<script src="https://code.jquery.com/jquery-1.12.4.js" type="text/javascript"></script>
<script>
$('input[type=checkbox]').change(function() {
if ($(this).is(":checked")) {
var id = $(this).val(); //The value bound in the checkbox
var row = $(this).parent("td").parent("tr");
ProductId = row.find("[name='Id']").text();
ProductName = row.find("[name = 'Name']").text();
var data = { ProductId: parseInt(ProductId), ProductName: ProductName };
var cart = new Array();
cart.push(data);
var viewmodel = { cart: cart};
$.ajax({
type: "post",
url: '/Home/Test',
data: JSON.stringify(viewmodel),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(result) {
//your own processing logic
},
error: function(error) { }
});
}
});
</script>
I send all the data out, you can just send an ID if you want and then do the following in the controller.
Test Result:

Validation and submit button don't function together in PartialView while using a composite model

Validation in my forms are defined in my Model.
If I don't include these two lines in my view:
$("#frmNewTemplate").removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#frmNewTemplate");
The submit button works fine, but validation doesn't work. If I include these, validation starts working and the submit button doesn't work anymore.
I try to do the validation through my model.
My model:
public class TemplateDTO : DTOBase
{
public virtual int ID { get; set; }
[Required(ErrorMessage="فيلد ضروري")]
[RegularExpression("^[a-zA-z0-9\\-\\. ]+$", ErrorMessage = "کاراکترهاي وارد شده در محدوده کاراکترهاي مجاز نمي باشند")]
public virtual string Name { get; set; }
[RegularExpression("^[a-zA-zآ-ي0-9\\-\\. ]+$", ErrorMessage = "کاراکترهاي وارد شده در محدوده کاراکترهاي مجاز نمي باشند")]
public virtual string Name_Fr { get; set; }
public virtual IList<TemplateDetailsDTO> LstDetails { get; set; }
}
My composite model:
public class TemplateViewModel
{
public TemplateDTO Template { get; set; }
public List<TemplateFieldsDTO> TemplateFeilds { get; set; }
public int[] oSelectedFieldsDTO { get; set; }
public string Text { get; set; }
public bool NextLine { get; set; }
}
My Controller (ActionResult which calls the view and JsonResult which is the answer):
public ActionResult _NewTemplate()
{
if (myGlobalVariables.AllTemplateFieldsDTO == null)
{
TemplateFieldsClientService oTemplateFieldsClientService = new TemplateFieldsClientService();
myGlobalVariables.AllTemplateFieldsDTO = oTemplateFieldsClientService.GetAll();
}
TemplateDTO oTemplateDTO = new TemplateDTO();
oTemplateDTO.LstDetails = new List<TemplateDetailsDTO>();
TemplateViewModel x = new TemplateViewModel();
x.TemplateFeilds = myGlobalVariables.AllTemplateFieldsDTO;
x.Template = oTemplateDTO;
return PartialView(x);
}
[HttpPost]
public JsonResult _NewTemplate(TemplateViewModel oTemplateViewModel)
{
if (ModelState.IsValid)
{
if (oTemplateViewModel.Template != null)
{
if (oTemplateViewModel.Template.Name == null)
{
throw new System.ArgumentNullException("Parameter can not be null", "oTemplateDTO");
}
string strAttr = "";
if (oTemplateViewModel.NextLine)
strAttr = "\n";
List<TemplateDetailsDTO> LstTemDetails = new List<TemplateDetailsDTO>();
int Position = 0;
if (oTemplateViewModel.oSelectedFieldsDTO != null)
{
foreach (var i in oTemplateViewModel.oSelectedFieldsDTO)
{
TemplateDetailsDTO TempDetls = new TemplateDetailsDTO();
TempDetls.PositionNumber = ++Position;
TempDetls.Attributes = strAttr;
TemplateFieldsDTO OTemplateFieldsDTO = myGlobalVariables.AllTemplateFieldsDTO.Find(x => x.ID == i);
TempDetls.ObjFields = OTemplateFieldsDTO;
TempDetls.ObjTemplate = oTemplateViewModel.Template;
LstTemDetails.Add(TempDetls);
}
}
oTemplateViewModel.Template.LstDetails = LstTemDetails;
oTemplateClientService.AddNewTemplate(oTemplateViewModel.Template);
myGlobalVariables.AllTemplateDTO = oTemplateClientService.GetAllTemplate();
log.Info("Template added to Database.");
return Json(new { Result = "OK", Message = "عمليات ثبت با موفقيت انجام شد" }, JsonRequestBehavior.DenyGet);
}
else
{
return Json(new { Result = "Error", Message = "لطفا فيلدها را وارد نماييد" }, JsonRequestBehavior.DenyGet);
}
}
else
{
return Json(new { Result = "Error", Message = "لطفا فيلدها ي ضروري را وارد نماييد" }, JsonRequestBehavior.DenyGet);
}
}
Code for my view:
#model IAC.SMS.MvcApp.Controllers.TemplateViewModel
<script type="text/javascript">
$(function () {
$("#frmNewTemplate").removeData("validator").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#frmNewTemplate");
$('#btnAdd').click(function () {
$('#ListBoxSource').find('option:selected').appendTo('#oSelectedFieldsDTO');
})
$('#btnDelete').click(function () {
$('#oSelectedFieldsDTO').find('option:selected').appendTo('#ListBoxSource');
});
$('#btnUp').click(function () {
var selectedOption = $('#oSelectedFieldsDTO').find('option:selected');
var prevOption = $('#oSelectedFieldsDTO').find('option:selected').prev("option");
if ($(prevOption).text() != "") {
$(selectedOption).remove();
$(prevOption).before($(selectedOption));
}
});
$('#btnDown').click(function () {
var selectedOption = $('#oSelectedFieldsDTO').find('option:selected');
var nextOption = $('#oSelectedFieldsDTO').find('option:selected').next("option");
if ($(nextOption).text() != "") {
$(selectedOption).remove();
$(nextOption).after($(selectedOption));
}
});
});
function display() {
var dpt = document.getElementById("oSelectedFieldsDTO");
if (dpt.options[dpt.selectedIndex].text == "Text") {
document.getElementById("Text").disabled = false;
}
};
function SelectAllItems() {
$("#oSelectedFieldsDTO").each(function () {
$("#oSelectedFieldsDTO option").attr("selected", "selected");
});
};
//functions for ajax begin form
function Refresh() {
window.location.href = "#Url.Action("ListTemplate", "Template")" + "/";
}
function Success(data) {
if (data.Result == "OK") {
jSuccess(
data.Message,
{
autoHide: true, // added in v2.0
clickOverlay: false, // added in v2.0
MinWidth: 200,
TimeShown: 1500,
ShowTimeEffect: 1000,
HideTimeEffect: 500,
LongTrip: 20,
HorizontalPosition: 'center',
VerticalPosition: 'center',
ShowOverlay: true,
ColorOverlay: '#000',
OpacityOverlay: 0.3,
});
Refresh();
}
else {
jSuccess(
data.Message,
{
autoHide: true, // added in v2.0
clickOverlay: false, // added in v2.0
MinWidth: 200,
TimeShown: 1500,
ShowTimeEffect: 1000,
HideTimeEffect: 500,
LongTrip: 20,
HorizontalPosition: 'center',
VerticalPosition: 'center',
ShowOverlay: true,
ColorOverlay: '#000',
OpacityOverlay: 0.3,
});
}
}
function Fail() {
jSuccess(
'ارتباط برقرار نشد',
{
autoHide: true, // added in v2.0
clickOverlay: false, // added in v2.0
MinWidth: 200,
TimeShown: 1500,
ShowTimeEffect: 1000,
HideTimeEffect: 500,
LongTrip: 20,
HorizontalPosition: 'center',
VerticalPosition: 'center',
ShowOverlay: true,
ColorOverlay: '#000',
OpacityOverlay: 0.3,
});
}
</script>
#using (Ajax.BeginForm("_NewTemplate", "Template", new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "Success",
OnFailure = "Fail",
LoadingElementId = "Loading"
}, new { #id = "frmNewTemplate" }))
{
<table id="tblDetails" class="dataInput" style="width:500px;">
<tr>
<td></td>
<td></td>
<td></td>
<td>
<label>
ليست مبدا
</label>
</td>
</tr>
<tr>
<td>
<label>
نام قالب
</label>
</td>
<td>
#Html.TextBoxFor(model => model.Template.Name)
<label style="color:red; font-weight:bold;">*</label>
#Html.ValidationMessageFor(model => model.Template.Name)
</td>
<td></td>
<td rowspan="3">
#Html.ListBox("ListBoxSource", new SelectList(Model.TemplateFeilds, "ID", "Name", 1), new { size = 10 , style = "width:200px"})
</td>
</tr>
<tr>
<td>
<label>
توضيحات
</label>
</td>
<td>
#Html.TextBoxFor(model => model.Template.Name_Fr)
</td>
</tr>
<tr>
<td>
<label>
پيام تکميلي
</label>
</td>
<td>
#Html.TextBoxFor(model => model.Text , new { disabled="disabled"})
</td>
<td>
</td>
</tr>
<tr>
<td>
#Html.CH_CheckBoxFor(model=>model.NextLine, "خط بعد", false, false)
</td>
<td></td>
<td></td>
<td>
<button class="fixed button" id="btnAdd" type="button">اضافه<span class="left"></span> </button>
<button class="fixed button" id="btnDelete" type="button">حذف<span class="right"></span> </button>
</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td>
<label>
ليست مقصد
</label>
</td>
</tr>
<tr>
<td>
</td>
<td></td>
<td></td>
<td>
#Html.ListBoxFor(model => model.oSelectedFieldsDTO, new SelectList(Model.Template.LstDetails, "ID", "Name", 1), new { size = 10, style = "width:200px", onchange = "display()" })
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
</td>
<td>
<button class="fixed button" id="btnUp" type="button">بالا<span class="up"></span> </button>
<button class="fixed button" id="btnDown" type="button">پايين<span class="down"></span> </button>
</td>
</tr>
<tr>
<td>
#Html.HiddenFor(model=>model.Template.ID)
</td>
</tr>
</table>
<table>
<tr>
<td></td>
<td>
<div>
<button class="fixed button" type="submit" onmouseover="SelectAllItems()">ذخيره</button>
</div>
</td>
</tr>
</table>
}
Please tell me if I should include any more code.
My problem is that when I include the two lines code I mentioned above in my View to have validation, submit button in my PartialView won't function anymore, and the control doesn't go to the JsonResult function of my controller.
Thanks in Advance.
Update jquery.validate.min.js to version v1.12.0 - 4/1/2014 .
I hope you get the problem solved .

How to display text from a dropdown in MVC

I have a partial view that has to display records on the change of dropdown. The values are coming correctly but it is not being displayed in the tex boxes. Please help. THe code of my partial view looks like below
#using (Ajax.BeginForm("W2State", new AjaxOptions() { UpdateTargetId = "model", OnSuccess = "w2Updated", InsertionMode = InsertionMode.Replace, HttpMethod = "Post" } ))
{
<fieldset id="currencyView" class="detailView">
<table>
<tr>
<td style="width: 100px;">Select Agency </td>
<td>
#*#Html.DropDownListFor(model => model.ReportingAgencies, new SelectList(Model.ReportingAgencies, "SelectedAgency.AgencyGuid", "SelectedAgency.Name"), new { id = "dropDownReportAgencies" })*#
#Html.DropDownListFor(model => model.ReportingAgencies, new SelectList(Model.ReportingAgencies, "SelectedAgency.AgencyGuid", "SelectedAgency.Name"), "--Select An Agency--", new { id = "dropDownReportAgencies" })
</td>
</tr>
<tr class="seperator"></tr>
<tr class="seperator"></tr>
<tr>
<td style="width: 100px;">#Html.LabelFor(model => model.W2StateLocal.Wages)</td>
<td> #Html.TextBoxFor(model => model.W2StateLocal.Wages)</td>
</tr>
<tr>
<td style="width: 100px;">#Html.LabelFor(model => model.W2StateLocal.Tax)</td>
<td>#Html.TextBoxFor(model => model.W2StateLocal.Tax)</td>
</tr>
</table>
<div id="rightButtonControls">
#if (Model.IsEditable)
{
<button id="btnSave" value="save">Save</button>
}
</div>
</fieldset>
}
#Html.HiddenFor(model => model.CompanyId, new { id = "CompanyId" })
#Html.HiddenFor(model => model.EmployeeId, new { id = "EmployeeId" })
#Html.HiddenFor(model => model.FilingYear, new { id = "FilingYear" })
<script type="text/javascript">
$(document).ready(function () {
$("#divLoader").css('display', 'none');
$('#dropDownReportAgencies').change(function () {
var selectedAgency = $('#dropDownReportAgencies option:selected').val();
var CompanyId = $('#CompanyId').val();
var EmployeeId = $('#EmployeeId').val();
var FilingYear = $('#FilingYear').val();
var url = '#Url.Action("W2State", "W2Generation")';
$.get(url, { agencyId: selectedAgency, companyId: CompanyId, employeeId: EmployeeId, filingYear: FilingYear },
function (data) {
});
});
});
You want to get text from dropdown in mvc through jQuery...
Your code is right but just missing something.. You used
var selectedAgency = $('#dropDownReportAgencies option:selected').val();
but instead of 'val' you have to use 'text'.. it means
var selectedAgency = $("#dropDownReportAgencies option:selected").text();
Try this....

Parameters from view not getting to controller action method

I'm implementing Troy Goode's PagedList in one of my views (ASP.NET MVC 3 Razor). The challenge I'm having is when I click on a page number link, the request is routed to my HttpGet method, which just returns the empty page (ready for input).
My View Model:
public class SearchViewModel
{
public SelectList IndustrySelectList { get; set; }
public IPagedList<KeyValuePair<string, SearchResult>> SearchResults { get; set; }
public PagingInfo PagingInfo { get; set; }
}
Controller:
[HttpGet]
public ViewResult Search(string searchTerm = "")
{
SearchViewModel vm = new SearchViewModel
{
IndustrySelectList = new SelectList(_Industries.AsEnumerable(), "IndustryId", "IndustryName"),
PagingInfo = new PagingInfo
{
CurrentPage = 1,
ItemsPerPage = 25,
TotalItems = 0
}
};
return View(vm);
}
[HttpPost]
public ActionResult Search(string[] industries, string searchTerm = "", int page = 1)
{
SearchViewModel vm = null;
_url = "http://localhost/MasterNode/masternode.cgi?zoom_query={" + searchTerm + "}&zoom_xml=1&zoom_page={startPage?}&zoom_per_page=1000";
StringBuilder sb = new StringBuilder();
int pageSize = 5;
if (string.IsNullOrEmpty(searchTerm))
{
vm = new SearchViewModel
{
IndustrySelectList = new SelectList(_Industries.AsEnumerable(), "IndustryId", "IndustryName")
};
}
else
{
_request = new SearchRequest(SearchRequest.EnvironmentTypes.Development, "", _url, searchTerm, SearchRequest.SearchType.AllWords, 1000);
sb.Append(GetResults(_url));
_results = new Dictionary<string, SearchResult>();
ParseResults(sb);
GetDetailInformationForResults(searchTerm);
vm = new SearchViewModel
{
IndustrySelectList = new SelectList(_Industries.AsEnumerable(), "IndustryId", "IndustryName"),
SearchResults = _results.ToList<KeyValuePair<string, SearchResult>>().ToPagedList(1, 25),
PagingInfo = new PagingInfo
{
CurrentPage = page,
ItemsPerPage = pageSize,
TotalItems = _results.Count()
}
};
}
return View(vm);
}
View:
#model MultiView.OmniGuide.ViewModels.SearchViewModel
#using MultiView.OmniGuide.HtmlHelpers
#using PagedList
#using PagedList.Mvc
#{
ViewBag.Title = "Search";
}
<link href="/Content/PagedList.css" rel="stylesheet" type="text/css" />
#using (Html.BeginForm("Search", "Home"))
{
#Html.HiddenFor(c => c.IndustrySelectList)
#Html.HiddenFor(c => c.PagingInfo)
#Html.HiddenFor(c => c.SearchResults)
<table width="70%">
<tr>
<td colspan="2" style="background: #fff">
<input id="searchTerm" name="searchTerm" type="text" class="SearchBox" style="width: 450px" />
<input type="submit" class="SearchButton" value=" " />
</td>
</tr>
<tr align="left">
<td align="left" style="background: #fff">
#Html.ActionLink("MultiView corporate site", "Search")
</td>
</tr>
<tr>
<td colspan="1" align="center" style="width: 450px">
#{
Html.Telerik().PanelBar()
.Name("searchPanel")
.Items(title =>
{
title.Add()
.Text("Filter by Industry")
.Content(() =>
{
#Html.RenderPartial("_Industry", #Model);
});
})
.Render();
}
</td>
</tr>
<tr><td colspan="2"></td></tr>
</table>
<br />
if (Model.SearchResults != null)
{
<table width="70%">
<tr>
<th>
Company Image
</th>
<th class="tableHeader">
Company Name Here
</th>
<th class="tableHeader">
Website
</th>
</tr>
#foreach (KeyValuePair<string, MultiView.OmniGuide.Models.SearchResult> itm in Model.SearchResults)
{
<tr>
<td align="left" style="width: 15%">
#itm.Value.DetailedInfo.LogoURL
</td>
<td align="left" style="width: 60%">
<p style="text-align: left">
#itm.Value.DetailedInfo.DescriptionAbbreviated
<br />
</p>
#Html.AnchorLink(itm.Value.FoundURL, itm.Value.FoundURL)
</td>
<td style="width: 25%">
#itm.Value.FoundURL
</td>
</tr>
}
</table>
#Html.PagedListPager((IPagedList)Model.SearchResults, page => Url.Action("Search", "Home", new { page }))
}
}
When text is supplied in the input box and the button is clicked, the requested is routed to the HttpPost method. In looking at the request.form values, all expected data but paging information is present.
?HttpContext.Request.Form.AllKeys
{string[5]}
[0]: "IndustrySelectList"
[1]: "PagingInfo"
[2]: "SearchResults"
[3]: "searchTerm"
[4]: "industries"
Any help with this would be very much appreciated!
By clicking the button you are submitting the form which is why it is doing the httppost. The next page link is hitting the httpget correctly but you are not passing it any information to so that it knows what to get. The get needs other information, like what page you are wanting.
The page number links fire a GET request, so you'll need to make sure that your GET action can handle the full search as well, so will need to get the page number and industries array - using defaults for when those parameters aren't available.
e.g.
[HttpGet]
public ViewResult Search(string searchTerm = "", int page = 1,
string industries = "")
{
//.....
}
You'll need to modify the pager link like this to pass industries to the get action.
#Html.PagedListPager((IPagedList)Model.SearchResults, page => Url.Action("Search", "Home", new { page, industries = string.Join(",", Model.IndustrySelectList.Where( x => x.Selected).Select( x => x.Text)) }))
It's not clear to me from your code where the post action is getting string[] industries from, or what it is doing with it, but you will need some way of passing this same this to your get action, probably as a single string that is comma separated. The example I've provided assumed you are taken it from the select list on the viewmodel

To get the value of check boxes from a list of dynamicallly created check boxes in razor view engine

How to find the values of checkboxes(i.e., whether checked or not) from a list of dynamically created check boxes in razor view engine? the code runs as follows...
#foreach (var item in Model))
{
<tr>
<td class="Viewtd">
#Html.ActionLink(item.Title, "Edit", new { id = item.id})
</td>
<td>
#Html.CheckBox("ChkBox"+item.ThresholdID , false, new { id = item.id})
</td>
</tr>
}
How to get those check boxes values in the controller?
Do it the proper way: using view models and editor templates.
As always start by defining a view model:
public class MyViewModel
{
public string Title { get; set; }
public string Id { get; set; }
public bool IsThreshold { get; set; }
}
then a controller to populate this view model :
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new[]
{
new MyViewModel
{
Id = "1",
Title = "title 1",
IsThreshold = false,
},
new MyViewModel
{
Id = "2",
Title = "title 2",
IsThreshold = true,
},
new MyViewModel
{
Id = "3",
Title = "title 3",
IsThreshold = false,
},
};
return View(model);
}
[HttpPost]
public ActionResult Edit(MyViewModel model)
{
// This action will be responsible for editing a single row
// it will be passed the id of the model and the value of the checkbox
// So here you can process them and return some view
return Content("thanks for updating", "text/plain");
}
}
and then the Index view (~/Views/Home/Index.cshtml):
#model IEnumerable<MyViewModel>
<table>
<thead>
<tr>
<th></th>
<th>Threshold</th>
</tr>
</thead>
<tbody>
#Html.EditorForModel()
</tbody>
</table>
and finally the editor template (~/Views/Home/EditorTemplates/MyViewModel.cshtml):
#model MyViewModel
#{
ViewData.TemplateInfo.HtmlFieldPrefix = "";
}
<tr>
#using (Html.BeginForm("Edit", "Home"))
{
#Html.HiddenFor(x => x.Id)
#Html.HiddenFor(x => x.Title)
<td><input type="submit" value="#Model.Title" /></td>
<td>#Html.CheckBoxFor(x => x.IsThreshold)</td>
}
</tr>

Resources