I have a select that now needs to select and save more than one option. His FrontEnd part is already done, but BackEnd is not.
I need this select to save the selected values, for that it will need to loop the code, because at the moment it only saves one value.
However I don't know how to loop this code so that it saves all values and stops giving an error.
Screen with the selected values and their codes:
enter image description here
Select html code:
<div class="form-group pmd-textfield">
<label for="TipoPenalAntecedenteCriminal" class="espacamentoLabels">
Tipo Penal Principal
</label>
<select asp-items="Model.ListTipoPenal"
name="COD_TIPO_PENAL_PRINCIPAL"
id="TipoPenalAntecedenteCriminal"
form="formAntecedenteCriminal"
class="select-codigo" multiple
onchange="mostrarOutroDeCombo(this, 'OutroTipoPenalAntecedenteCriminal');">
<option value="">Selecione a relação</option>
</select>
</div>
Code Controller:
this is the code that I need to loop to save all values
[HttpPost]
public JsonResult SalvarAntecedenteCriminal(IFormCollection form)
{
#region GET DADOS DO USUARIO
var identity = (ClaimsIdentity)User.Identity;
string usuarioLogado = identity.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
#endregion
_logger.LogInformation(EventosLog.Get, "Usuário: {Usuario} | Salvando Antecedente criminal de autor com o código {codigo}.", usuarioLogado, form["COD_AUTOR"]);
string codAntecedente = string.IsNullOrEmpty(form["COD_AUTOR_ANTECEDENTES_CRIMINAIS"]) ? "0" : (string)form["COD_AUTOR_ANTECEDENTES_CRIMINAIS"]
, codUF = string.IsNullOrEmpty(form["COD_UF"]) ? "0" : (string)form["COD_UF"]
, codTipoPenal = string.IsNullOrEmpty(form["COD_TIPO_PENAL_PRINCIPAL"]) ? "0" : (string)form["COD_TIPO_PENAL_PRINCIPAL"];
DateTime? ocorrenciaData = string.IsNullOrEmpty(form["OcorrenciaData"]) ? null : (DateTime?)DateTime.Parse(form["OcorrenciaData"]);
var antecendeteCriminal = new AutorAntecedentesCriminaisModel
{
COD_AUTOR = int.Parse(form["COD_AUTOR"]),
COD_AUTOR_ANTECEDENTES_CRIMINAIS = int.Parse(codAntecedente),
OcorrenciaNumero = form["OcorrenciaNumero"],
COD_UF = int.Parse(codUF),
OcorrenciaData = ocorrenciaData,
COD_TIPO_PENAL_PRINCIPAL = int.Parse(codTipoPenal),
OutroTipoPenal = form["OutroTipoPenal"]
};
try
{
antecendeteCriminal.COD_AUTOR_ANTECEDENTES_CRIMINAIS = antecendeteCriminal.Insert(usuarioLogado);
}
catch (Exception excecao)
{
_logger.LogError(EventosLog.FormularioSalvarErro, excecao,
"Usuário: {Usuario} | Falha ao salvar antecedente criminal de autor com o código {codigo} devido à exceção.",
usuarioLogado, form["COD_AUTOR"]);
if (_env.IsDevelopment())
throw;
return Json(null);
}
return Json(antecendeteCriminal);
}
Code image, the part in yellow and where the error hits when saving.
In "COD_TIPO_PENAL_PRINCIPAL = int.Parse (codTipoPenal)," it is receiving the values, but it is not saving.
enter image description here
The COD_TIPO_PENAL_PRINCIPAL should be a int array if you wany to save all the values.
public int[] COD_TIPO_PENAL_PRINCIPAL { get; set; }
Related
In my ASP.NET Core web application I have a partial view that will need to be placed in several views and be able to respond to dynamic data that will vary based on the view that's rendering this partial at the time. The red box in the image blow represents the area the partial is rendered.
The partial is essentially a Select that will call a Stored Procedure and return a datatable and render out the table to the partial view. I am able to select an option on the page and have it call the SP and see all relevant data from the datatable and can write that out on the page no problem. The problem I am having is that every time the partial refreshes via ajax, the Select returns to the default "Select" value and does not keep the previously selected option selected.
For the sake of brevity, assume that the FeedbackQueries object just contains 4 string elements.
_FeedbackQueryResultPartial.cshtml
#using Contract.Shared;
#model FeedbackQueries
<style>
#select {
margin: auto;
text-align: center;
}
</style>
<div id="feedbackQueryResultPartial">
<div style="height:25px;">
<div id="select">
<select name="StoredProcs" id="StoredProcs" onchange="selectQuery()">
<option value="Select">Select</option>
#foreach (FeedbackQuery query in Model.Queries)
{
#Html.Raw($"<option value='{query.SprocName}'>{query.SprocName}</option>");
}
</select>
</div>
<div id="feedbackQueryDiv" class="row">
#if (Model.FeedbackQueryResults.Rows.Count > 0)
{
<h3>DataTable goes here</h3>
}
else
{
<h3>No rows were returned from your query. Please select another.</h3>
}
</div>
</div>
</div>
Processing.cshtml
#using Contract.Parent
#using Contract.Shared
#model Processing
<script>
function showFeedbackPartial(x, y, z, q) {
$.ajax({
cache: false,
url: '#Url.Action("GetFeedbackQueryDatatable", "Client")',
type: 'POST',
data: { databaseConnectionString: x, storedProcedure: y, page: z, Model: q },
success: function (result) {
var selected = $('#StoredProcs').val();
console.log(selected);
if (result.rowCount > 0) {
console.log(result.rowCount);
var databaseConnectionString = x;
var storedProcedure = y;
var page = z;
var model = q;
var url = '#Url.Action("ViewFeedbackQueryPartial", "Client")';
$("#feedbackQueryResultPartial").load(url, { databaseConnectionString, storedProcedure, page, model });
}
else {
document.getElementById('feedbackQueryDiv').innerHTML = '<h3>No rows were returned from your query. Please select another.</h3>';
}
$('#StoredProcs').val(selected);
$("#StoredProcs option[value='Select']").remove();
}
});
}
</script>
<script>
function selectQuery() {
var e = document.getElementById('StoredProcs');
var ev = e.options[e.selectedIndex].text;
var p = 'Processing';
var model = #Html.Raw(Json.Serialize(Model.FeedbackQueries));
console.log(model);
showFeedbackPartial('#Model.Client.DatabaseConnectionString', ev, p, model);
}
</script>
<script>
$(document).ready(function () {
document.getElementById('feedbackQueryDiv').innerHTML = '<h3>Select a query to view feedback.</h3>';
});
</script>
}
<form method="post" enctype="multipart/form-data">
...
<partial name="_FeedbackQueryResultPartial" for="#Model.FeedbackQueries" />
...
</form>
Controller actions that render the Processing view
[HttpGet]
public IActionResult Processing(int Id)
{
ViewBag.Id = Id;
Processing processing = new Processing();
//Get pertinent information for Client
processing.Client = _clientProcessingService.GetSingleClient(Id, _appSettings.MOPConfigConnectionString);
processing.Client.DatabaseConnectionString = _clientProcessingService.GetClientConnectionFromConfig(processing.Client, _appSettings);
processing.Steps = _clientProcessingService.GetClientSteps(processing.Client.DatabaseConnectionString, "Processing");
processing.CurrMoInfo.CurrMo = _clientProcessingService.GetProcessingCurrMo(processing.Client.DatabaseConnectionString);
processing.FeedbackQueries = _clientProcessingService.GetFeedbackQueriesFromDb(processing.Client.DatabaseConnectionString, "Processing");
return View(processing);
}
[HttpPost]
public IActionResult Processing(Processing Model)
{
//Get pertinent information for Client
Model.Client = _clientProcessingService.GetSingleClient(Model.Client.ClientID, _appSettings.MOPConfigConnectionString);
Model.Client.DatabaseConnectionString = _clientProcessingService.GetClientConnectionFromConfig(Model.Client, _appSettings);
Model.Steps = _clientProcessingService.GetClientSteps(Model.Client.DatabaseConnectionString, "Processing");
Model.CurrMoInfo.CurrMo = _clientProcessingService.GetProcessingCurrMo(Model.Client.DatabaseConnectionString);
Model.FeedbackQueries = _clientProcessingService.GetFeedbackQueriesFromDb(Model.Client.DatabaseConnectionString, "Processing");
return View(Model);
}
Controller action that renders the partial
public IActionResult ViewFeedbackQueryPartial(string DatabaseConnectionString, string StoredProcedure, string Page, FeedbackQueries Model)
{
if(StoredProcedure == "Select")
{
return PartialView("_FeedbackQueryResultPartial", Model);
}
Model.FeedbackQueryResults = _clientProcessingService.GetFeedbackQueryDataTable(DatabaseConnectionString, Page, StoredProcedure);
return PartialView("_FeedbackQueryResultPartial", Model);
}
I have tried so many different ways of maintaining this value. Adding it to the model, adding it to the Viewbag and countless other methods of attempting to retain this value somewhere and regardless of success or failure, keep the value and change it to the selected option via javascript. It resets to "Select" every time the partial is reloaded after the ajax call is made.
This also presents another problem wherein, when I submit the form on the Processing view by clicking RUN the page will refresh and go to the next step in the process but ideally what should also happen is that the value in the partial is kept, the query is ran again and the user doesn't need to select a new value at any point unless they want to run a different SP to see different data in the table.
Is this even possible or am I trying to do this the entirely wrong way?
For your issue, you may need to pass the selected SprocName from Parent View to partial view with Model.
Add SelectedSprocName to FeedbackQueries
public class FeedbackQueries
{
public string SelectedSprocName { get; set; }
public List<FeedbackQuery> Queries { get; set; }
public FeedbackQueryResults FeedbackQueryResults { get; set; }
}
Change View to set SelectedSprocName
function showFeedbackPartial(x, y, z, q) {
$.ajax({
cache: false,
url: '#Url.Action("GetFeedbackQueryDatatable", "Process")',
type: 'POST',
success: function (result) {
var selected = $('#StoredProcs').val();
model.SelectedSprocName = selected;
var url = '#Url.Action("ViewFeedbackQueryPartial", "Process")';
$("#feedbackQueryResultPartial").load(url,{ databaseConnectionString, storedProcedure, page, model });
console.log('after load' + selected);
// your rest code
}
});
}
Partial View set selected option
#foreach (FeedbackQuery query in Model.Queries)
{
if (query.SprocName == Model.SelectedSprocName)
{
#Html.Raw($"<option value='{query.SprocName}' selected='true'>{query.SprocName}</option>");
}
else
{
#Html.Raw($"<option value='{query.SprocName}'>{query.SprocName}</option>");
}
}
I am building an app using MVC, and this question pertains to the Create page and action.
Lets say my model has 2 decimal properties along with other properties but aren't necessary for this example:
public class TestClass
{
public int ID { get; set; }
public decimal DecimalProperty { get; set; }
public decimal SecondDecimalProperty { get; set; }
// more properties below this, but deemed unnecessary for this question
}
Obviously these properties are non-nullable, so in my Create View they appear as so on page load (ignore the 2nd textbox):
Now my goal is to clear those textboxes out, so they are just blank.. so I used JS to achieve that by doing:
$(".clear-textbox").val("");
I put a class called clear-textbox on those input fields.. works perfectly.. but now in my HttpPost Create Action I have conditional statements checking to see if other fields are valid, and if not return the object.. like so:
if (object.property== 0)
{
ModelState.AddModelError("property", "This field is required!");
return View(object);
}
This results in the Create view to be redisplayed with the values that the user has already entered, along with an error message below the one property that needs to be changed.. and this is where the problem lies. Once the Create view is reloaded.. then so are the scripts for clear-textbox, resulting in DecimalProperty and SecondDecimalProperty to be empty text-boxes.. instead of keeping what the user originally entered for them.
So my question, is there another way to clear out textboxes for decimal properties other than using javascript?
Any help is appreciated.
UPDATE
Here is the cshtml.
<div class="form-group">
#Html.LabelFor(model => model.DecimalProperty, htmlAttributes: new { #class = "control-label col-md-4" })
<div class="col-md-8">
#Html.EditorFor(model => model.DecimalProperty, new { htmlAttributes = new { #class = "form-control clear-textbox" } })
#Html.ValidationMessageFor(model => model.DecimalProperty, "", new { #class = "text-danger" })
</div>
</div>
Either you have to do it via Javascript on load like following
$(".clear-textbox").each(function(){
if($(this).val() <= 0 )
$(this).val("");
});
OR
You can create your own MVC Html Helper which will do things as you need for your special needs. Let me know if you want code for that...
You can also refer this link
You can set the default value as a data- attribute of the textbox and clear it only if they match. Like:
$(".clear-textbox").each(function(){
var $this = $(this);
if( $this.val() == $this.data().defaultvalue ) $this.val('');
});
It's hard to come up with an answer without knowing how the text boxes are being rendered. However, I'm assuming you are using something like
#Html.TextBoxFor
or
#Html.EditorFor
There are two ways to do this.
1. Add a DisplayFormat attribute to the model fields and use EditorFor:
public class TestClass
{
public int ID { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:#.#}")]
public decimal DecimalProperty { get; set; }
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:#.#}")]
public decimal SecondDecimalProperty { get; set; }
}
#Html.EditorFor(model => model.DecimalProperty)
2. Use the inline format attribute:
#Html.TextBoxFor(model => model.DecimalProperty, "{0:#.#}")
Thanks in advance.
I have a Autocomplete Input Field where we can type the string and using jquery Autocomplete I get the dropdown from a JSP page and that JSP page calls the Java function to retreive the data from MYSQL.
the HTML code is as follows.
<form>
<input type="hidden" id="autosuggest" name="autosuggest" value="Y"/>
<input type="text" name="Category" id="searchp" value="">
<script>
$("#searchp").autocomplete({
delay: 100,
autoFocus: true,
selectFirst: true,
source: 'ProviderSuggest.jsp',
select: function (event, ui) {
$('#autosuggest').val('Y');
}
});
</script>
<input type="submit" value="Submit"/>
</form>
Below is the code for ProviderSuggest.jsp
<%#page import="java.util.Map"%>
<%#page import="java.util.HashMap"%>
<%#page import="com.google.gson.Gson"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.Iterator"%>
<%#page import="Functions.DBConnections"%>
<%#page import="java.util.List"%>
<%
String query = request.getParameter("term");
List<String> CategoryList = new DBConnections().GetCategoryList(query);
Iterator CatIterator = CategoryList.iterator();
String JCategory = "";
Map CategoryMap = new HashMap();
while (CatIterator.hasNext()) {
String Category = (String) CatIterator.next();
String CategoryID = (String) CatIterator.next();
CategoryMap.put(CategoryID, Category);
}
Gson gson = new Gson();
JCategory = gson.toJson(CategoryMap);
System.out.println(JCategory);
//out.print(JCountry);
out.print(JCategory);
%>
Below is the code for the Java Function to get the data from MySql
public static List GetCategoryList(String Keyword) {
List<String> CategoryList = new ArrayList<String>();
try {
Class.forName(driverName).newInstance();
Connection connection = DriverManager.getConnection(connectionURL + dbName, dbuserID, dbpwd);
PreparedStatement preStatement;
ResultSet resultSet;
String query = "SELECT Category, CategoryID FROM category WHERE Keywords LIKE '%" + Keyword + "%' AND ParentCatID != 0 Limit 10";
preStatement = connection.prepareStatement(query);
resultSet = preStatement.executeQuery(query);
while (resultSet.next()) {
CategoryList.add(resultSet.getString(1));
CategoryList.add(resultSet.getString(2));
}
resultSet.close();
preStatement.close();
connection.close();
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
Logger.getLogger(DBConnections.class.getName()).log(Level.SEVERE, null, ex);
}
return CategoryList;
}
If you see the ProviderSuggest.jsp is returning an Array with CategoryID and Category.
When I display them at the front end i am able to display Category and I am trying to set the Value of that Autocomplete Input Field as the CategoryID so that when I submit the form I only send the Category ID for further processing.
May I know what wrong I am doing as I am not able to set the Value of the Input Field to the CategoryID.
Thanks.
I'm not JQuery fan/expert, but the line $('#autosuggest').val('Y'); says set the value to const value Y, and it's not the value you got from the server?!
Plus set the content-type of response in jsp using
<%#page language="java" contentType="application/json;charset=UTF-8"
pageEncoding="UTF-8"%>
And the java code would be more better by having a sql-side function for calling the function(run query), and pass(escape) the value to the function via PreparedStatement
If you could make the response string like this, you can set key value pairs to text field.
Check below code:
var availableTags2 = [ {
label : "Category id1"
value : "Category val1",
}, {
label : "Category id2"
value : "Category val2",
} ];
Problem Statement: I want to change the display name of labels(#Html.LabelFor) in Razor view of MVC based on the display names which i get from db.
I have added the dropdown list of languages in the _Layout.cshtml
<li>#Html.Action("Index", "LanguageDropdown", new { languageid = Request["languageId"] })</li>
I have created one partial view for drop down:
#model ALCMS.Web.Models.Master_or_Configuration.LanguageDropdownModel
<script type="text/javascript">
function GetLanguage() {
var languageId = $('#LanguageId').val();
var Url = "#Url.Content("~/MasterConfigGeneral/GetLanguage")";
$.ajax({
url: Url,
dataType: 'json',
data: { LanguageId: languageId },
success: function (data) {
}
});
}
</script>
<div style="display:inline-block">
#Html.DropDownListFor(l => l.LanguageID, new SelectList(Model.Languages, "Value", "Text"), "Select Language", new { id = "LanguageId" ,onchange="GetLanguage()" })
</div>
Partial View Controller:
public ActionResult Index(string languageId)
{
//return View();
var languages = dbEntity.LookupLanguages;
var model = new LanguageDropdownModel
{
LanguageID = languageId,
Languages = languages.ToList().Select(l => new SelectListItem
{
Value = Convert.ToString(l.LanguageID),
Text = l.Name
})
};
return PartialView(model);
}
In Controller Json Result method:
public JsonResult GetLanguage(int languageID)
{
JsonResult jsResult = new JsonResult();
objdbGlobalTenant.ddlLanguage = (from lsr in dbEntity.LocaleStringResources
where lsr.LanguageID == languageID
select new SelectListItem()
{
Text = lsr.ResourceValue,
Value = lsr.ResourceName
}).Distinct().ToList<SelectListItem>();
//ViewBag.Language = objdbGlobalTenant.ddlLanguage;
jsResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jsResult;
}
Now everything is working fine.I'm able to get the selected langaugeID in Json Result method in Controller based on the change event of Language dropdown. Based on this Language ID i'm getting display names(ResourceValue) which i need to apply for the particular view.
Problems:
1>After getting the display names from db how to change display names
of particular view when language change event triggers.?? For
ex:Currently i'm seeing the Create.CSHTML. Now if i change the
language dropdown it should trigger Json Event in controller and
after getting values it should apply the values on the view which it
got from db.
Note: Dropdown is in Layout.cshtml(like master in .aspx)
2>Drop-down which i placed in Layout.cshtml is getting refreshed
every time new view is loaded which inherits(layout.cshtml).How to
make the controller to retain it's state during postback??
3>How to get the selected drop-down item from the layout in multiple
Controllers,to change the display name in each view based on the langaugeid
of dropdown in layout
How to do this??If i'm doing wrong suggest me some other ways...
Below are the suggestions :
Issue 1 :
You may keep one attribute in each label which identifies them uniquely.
Your HTML should render like following
<!-- For English -->
<label label-unique-name="Name">Name</label>
<label label-unique-name="Surname">Surname</label>
<!-- For French -->
<label label-unique-name="Name">nom</label>
<label label-unique-name="Surname">nom de famille</label>
<!-- For Spanish -->
<label label-unique-name="Name">nombre</label>
<label label-unique-name="Surname">apellido</label>
Here label-unique-name is your attribute, which will remain fixed for each language. Now when you change the language from dropdown you will bring the values like below.
<!-- For English -->
<label-unique-name:"Name",label-value:"Name">;<label-unique-name:"Surname",label-value:"Surname">
<!-- For French -->
<label-unique-name:"Name",label-value:"nom">;<label-unique-name:"Surname",label-value:"nom de famille">
<!-- For English -->
<label-unique-name:"Name",label-value:"nombre">;<label-unique-name:"Surname",label-value:"apellido">
Please note : this is for understanding only, it's not a JSON.
Now using jQuery go through each label and replace the label's value. Hope it'll help you.
Issue 2 :
You can save the selected language's value in session, and generate your dropdown accordingly.
#Html.DropDownListFor(l => l.LanguageID, new SelectList(Model.Languages, "Value", "Text"), !string.isNullorEmpty(HttpContext.Current.Sessions["Language"]) ? HttpContext.Current.Sessions["Language"] : "Select Language", new { id = "LanguageId" ,onchange="GetLanguage()" })
In this project we have two list, one for the dealer and the second for his products.
So far if you check one dealer we get back all the product for this specific dealer, it implemented in javascript (Json).
Html (5 :)
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>DealerProduct</legend>
<div class="editor-label">
#Html.LabelFor(model => model.DealerID)
</div>
<div class="editor-field">
#Html.DropDownList("DealerID", String.Empty)
#Html.ValidationMessageFor(model => model.DealerID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ProductID)
</div>
<div class="editor-field">
#Html.DropDownList("ProductID", String.Empty)
#Html.ValidationMessageFor(model => model.ProductID)
</div>
<p>
<input type="submit" value="#Shared.Add" />
</p>
</fieldset>
}
JavaScript (Json :)
<script type="text/javascript">
$(document).ready(function()
{
$("#DealerID").change(function ()
{
var self = $(this);
var items="";
var url = "";
url = "#Url.Action("GetDealerProducts","DealerProduct")/"+self.val();
$.ajaxSetup({ cache: false });
$.getJSON(url,function(data)
{
$.each(data,function(index,item)
{
items+="<option value='"+item.Value+"'>"+item.Text+"</option>\n";
});
$("#ProductID").html(items);
$.ajaxSetup({ cache: true });
});
});
});
</script>
Controller :
public ActionResult GetDealerProducts(int id)
{
Dealer currentDealer = db.Dealers.Single(p => p.UserName == User.Identity.Name);
Dealer subDealer = db.Dealers.Single(s => s.DealerID == id);
List<Product> productOpenToSale = new List<Product>();
foreach (var item in currentDealer.ProductToSale)
if (!subDealer.ProductToSale.ToList().Exists(e => e.ProductID == item.ProductID))
productOpenToSale.Add(item.Product);
List<SelectListItem> productOpenToSaleList = new List<SelectListItem>();
productOpenToSale.ForEach(item => productOpenToSaleList.Add(new SelectListItem { Value = item.ProductID.ToString(), Text = item.ProductName }));
return Json(productOpenToSaleList, JsonRequestBehavior.AllowGet);
}
What I really need is adding (a pairing of) products dealer, which he can sell in the future.
Current option is to add products one by one, the desire is to give the possibility of multiple selection of all products.
Maybe something like dynamic checkBoxList or an foreach on a List from the ViewModel who add input - checkbox like this, but I don't know how to fill it after the dealer has selected on the first list and receive all the selected product back on submit..
10X for any help!! (&& sorry for my bad English :)
you can change this line of code
#Html.DropDownList("ProductID", String.Empty)
with something like this
<select id="SelectedItemIds" multiple="multiple" name="SelectedItemIds">
and having a viewModel on the server like this
class MyViewModel
{
public int[] SelectedItemIds { get; set; }
public int DealerID {get;set;}
}
and having a controller like this
[HttpPost]
public ActionResult Index(MyViewModel myViewModel)
{
return View();
}
I have similar situation and made it works here:
enter link description here
but I don't know how to pass the actual text back. I can only pass the index of selected items back to the controller. If you figure it out let me know.
Make sure your select name matches your variable name in the model.