Html.ActionLink is not working in foreach loop - asp.net-mvc

I receive some data from another page. I try to loop through data and create a link. I get the data and put it in #Html.ActionLink(GroupID, "GroupActivity", "Home"). GroupID have value now.
But on screen it just shows the data but does not makes it a link.
<li>#Html.ActionLink("Timetable", "Timetable", "Home")</li>
<li>
<select class="form-control">
<option selected>Select Group</option>
#{ var GroupID = ""; }
#foreach (var item in Model)
{
<option>
#{
GroupID = item.GroupID.ToString();
ViewBag.SelectedGroup = GroupID;
}
#Html.ActionLink(GroupID, "GroupActivity", "Home")
</option>
}
</select>
</li>
enter image description here

You have to write there something like this:
Using Action link
#Html.ActionLink("Some text for link", "GroupActivity", "Home",new {GroupID=GroupID })
But in your case, this would not work because you are creating action link inside option which is invalid.
Using client side event (onchange)
$(function(){
$("#YourDropDownID").change(function(){
var selectedItem = $("#YourDropDownID option:selected").text();
var redirectURL = '#Url.Action("ActionName","ControllerName")';
window.location.href = redirectURL + "?item=" + selectedItem;
}
}

Related

how to get the selected value to input text box in thymeleaf

Onchange in the dropdown, dist_nm should be reflected in the text box..
Can someone help?
<select id="editDistName" th:field="*{districts}" th:onchange="selectedDistName();">
<option value="default">Select the District </option>
<option th:each="dist : ${districts}" th:value="${dist.dist_id}"
th:text="${dist.dist_nm}" th:selected="${dist.dist_nm}"/>
</select>
<input type="text" class="form-control" id="dist_nm" name="dist_nm"/>
1.) I don't think that your th:selected="..."-attribute has any effect.
2.) Try this js-code (using jquery):
function selectedDistName()
{
let txt = $("#editDistName option:selected").text();
console.log(txt);
$("#dist_nm").val(txt);
}
Comment if you are not using jquery.
Finally, I found a way to fetch the name through table by passing ID from Dropdown.
HTML - form
<div class="form-group">
<select id='DCode' name='DCode'>
<option th:each="dist : ${districts}"
th:value="${dist.dist_id}"
th:text="${dropDownItem.dist_nm}" />
</select>
</div>
<div class="form-group">
<div id="textBox"></div>
</div>
Repository -- fetching name through ID
#Query("SELECT name FROM Sample WHERE id =:ID ORDER BY id")
public String getName(#Param("ID") int code);
AjaxController
#RequestMapping(value="Ajax",method={ RequestMethod.GET, RequestMethod.POST })
public #ResponseBody String editName(#RequestParam(value="ID") int d_Code ) {
String name = rep.getName(d_Code);
return name;
}
JS-file /passing ID to get Name from table/
$(document).on("change", "#DCode", function() {
try {
var d_id= $("#DCode option:selected").val();
var params = {ID : d_id};
$.ajax({
type:'POST',
url:'/Ajax',
data:params,
success:function(responseJson){
var jSON_res = JSON.stringify(responseJson);
var d_Name = jSON_res.replace(/\"/g, "" ); //remove double quote from string
var text_val = "<input type='text' id ='new_name' name ='new_name' " +
" value =' "+d_Name+" ' />";
$("#textBox").empty().append(text_val);
}//success function
});
} catch(err) {
alert("Exception ::-- "+err);
}
});
I'm very new to spring boot and this is one of the way I tried.
Let me know, if there is better way of getting the result.
Thank you,

Not able to move attachments through kendo upload from one view to another view

We are working on Kendo MVC UI, where we are sending the data from one view to another view, all the data(testbox, dropdown) are getting passed to the next view except the attachments(pdf,xlsx).
Below is the code which in the controller which we have written to capture from view and save the data and pass the same data to the another view and bind the data to the kendo controls(upload control also)
public ActionResult SaveData(System.Web.Mvc.FormCollection form, IEnumerable<HttpPostedFileBase> files) // insert operation
{
//*************************//
if (form != null)
{
string ddluserexceptioncategory = Convert.ToString(form["txtexceptioncategory"], CultureInfo.InvariantCulture);
if (!string.IsNullOrEmpty(ddluserexceptioncategory))
{
ddluserexceptioncategory = ddluserexceptioncategory.Trim();
}
if (ddluserexceptioncategory == "User Management")
{
//Bind the data to the class object(_clsObj)
if (files != null)
{
TempData["FileName"] = files;
_clsObj.Files = files;
}
TempData["SecondViewData"] = _clsObj;
return RedirectToAction("ExceptionType", "Home", new { id = 0, regionId = _clsObj.RegionId, status1 = "New,In Progress", keyword1 = string.Empty });
}
}
string regions = "", statusValue = "";
if (form != null)
{
regions = form["hiddenregionselected"] + "";
statusValue = form["hiddenstatusselected"] + "";
}
return RedirectToAction("homepage", "Home", new { region = regions, status = statusValue });
}
Below is the code which we bind the request to the second
#if (TempData["FileName"] != null)
{
IEnumerable<HttpPostedFileBase> firstFile = (IEnumerable<HttpPostedFileBase>)TempData["FileName"];
<div class="k-dropzone">
<div class="k-button k-upload-button">
<input name="files" type="file" data-role="upload" multiple="multiple" autocomplete="off" tabindex="-1" class="valid" style="display: none;">
<input id="files" name="files" type="file" data-role="upload" multiple="multiple" autocomplete="off">
<ul id="files1" class="k-upload-files k-reset">
#foreach (var file in firstFile)
{
string filename= Path.GetFileName(file.FileName);
<li class="k-file" data-uid="7aa03676-4dac-468e-b34a-99ac44d23040">
<span class="k-icon k-success">uploaded</span>
<span class="k-filename" title="#filename">#filename</span>
<strong class="k-upload-status">
<span class="k-icon k-delete"></span>
</strong>
</li>
}
</ul>
</div>
</div>
<script>
jQuery(function()
{jQuery("#files").kendoUpload(
{"select":uploadselect,
"localization":{"select":"Browse file",
"headerStatusUploading":"uploading..",
"headerStatusUploaded":"uploded.."},
"async":{"saveUrl":"/Home/Save",
"autoUpload":false,"removeUrl":
"/Home/Remove"}});});
</script>
}
else
{
#(Html.Kendo().Upload().Name("files").Async(a => a.Save("Save", "Home").Remove("Remove", "Home").AutoUpload(false)).Multiple(true).Messages(m =>
{
m.Select("Browse file");
}).Events(events => events.Select("uploadselect")))
}
Any suggestions or help is much appreciated.
My guess is that the issue is coming from using TempData to get this data from your markup to your controller or vice versa.
As you are likely aware, anything you put into TempData is discarded after the next request completes (Using Tempdata in ASP.NET MVC - Best practice, http://www.codeproject.com/Articles/476967/What-is-ViewData-ViewBag-and-TempData-MVC-Option).
I would suggest to try using the ViewBag to prove this theory. If it proves out you might think about passing this data as part of a complex object instead of using MVC's data dictionaries.

Make a condition to display a partial view MVC 4

I want to display a PartialView inside a View with a shared layout, the thing is that I want to render this partial from a select value.
So, I want to know how to trigger the view from Controller depending of the selected value in the select element.
Here's the code:
EDIT
Administrador.cshtml
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Seleccione Cartera:</td>
<td>
<select id="SeleccionCartera" name="SeleccionCartera">
<option value="">Seleccione Cartera</option>
<option value="0">Activa</option>
<option value="1">Conservadora</option>
<option value="2">Moderada</option>
<option value="3">Nueva</option>
</select>
</td>
<td>
<button name="btnBuscarRegistros" class="btnExportar">Buscar</button>
</td>
</tr>
</table>
<div id="prueba" name="prueba">
//Here is where my partial displays info.
</div>
Functions.js
$("#SeleccionCartera").change(function () {
var val = $("#SeleccionCartera").val();
$("#prueba").load('Admin/SeleccionCartera/?value =' + val);
});
AdminController.cs
public ActionResult SeleccionCartera(int id)
{
string partial = "";
if(id==3)
{
partial = "_NuevaCartera";
}
return PartialView(partial);
}
If the user select "Nueva", I want to display a PartialView, if the user choose "Activa" I want to display another PartialView (or the same) from Controller.
Thanks for the help!
PD: Sorry for my English, I'm Chilean.
There's numerous ways to do this, Here is one of them:
Set up an empty Div, and use JQuery's load function
<div id="MyPartial">
</div>
$("#MyDDL").change(function () {
var val = $("#MyDDL").val(); // this should be an int
$("#MyPartial").load('Home/ViewPartial/?value =' + val);
});
Controller
public ActionResult ViewPartial(int value)
{
// do stuff
return PartialView("_MyPartial",model);
// if you want to have a "dynamic" partial view this should work
//string partialViewName = "name";
// return PartialView(partialViewName,model);
}
an idea:
you could put your partial view within a div and give it an Id.
also, give your select control an Id.
Then create a javascript function which triggered by the onselect event of the select element.
in that js function check the selected value if it's Nueva? then make the partial view div visible if not hide the div
set the partial view div by default hidden.
please check this similar example: http://www.rajeeshcv.com/post/details/27/asp-net-mvc-conditional-rendering-partial-views

Set selected value of a dropdown in Razor view

I am trying to set the selected value in a dropdown in a razor view.
<select id="drpStatus" name="status">
<option value="A">Active</option>
<option value="S">Suspended</option>
<option value="T">Terminated</option>
<option value="D">Deleted</option>
</select>
//I am trying with the below code, based on the value in Model, I want to set the particular option as selected
<option selected=#{if(#Model!=null && #Model.Status=='A'){'selected'}} value="A">Active</option>
Above code is not working, please let me know if I am working in a right direction or is there any other/better way to achieve it.
Try this from your controller
Controller :
var record = db.Records.Find(id);
ViewBag.DropStatus = new SelectList(ListOfStatus, record.Status);
The first parameter for SelectList should be an IEnumerable which will serve as the data source for your DropDownList, the second parameter is for the selected value, so just pass the status property of the record you want to edit.
View:
#Html.DropDownList("Status", string.Empty)
The first parameter is the name of the ViewBag we assigned in the controller, it will also serve as the name when you post the data. Hope I've made myself clear.
The following is one of some possible solutions
#{
ViewBag.Title = "Index";
Func<char, MvcHtmlString> function = (c) => Model != null && Model.Status == c
? MvcHtmlString.Create("selected='selected'")
: MvcHtmlString.Empty;
}
<h2>Index</h2>
<select id="drpStatus" name="status">
<option #function('A') value="A">Active</option>
<option #function('S') value="S">Suspended</option>
<option #function('T') value="T">Terminated</option>
<option #function('D') value="D">Deleted</option>
</select>
It would be better to use SelectList in your ViewModel.
Another possible solution is using Razor's helper tag in the cshtml:
#helper SetGender(string dropdownvalue)
{
var selected = string.Format("value=\"{0}\"", dropdownvalue);
if ((string.IsNullOrEmpty(dropdownvalue) && string.IsNullOrEmpty(User.GetClaim(ClaimTypes.Gender.ToString()))) ||
(User.GetClaim(ClaimTypes.Gender.ToString()) == dropdownvalue))
{
selected = string.Concat("selected='selected' ", selected);
}
#Html.Raw(selected);
}
<select name="gender">
<option #SetGender("") >-not set-</option>
<option #SetGender("male") >male</option>
<option #SetGender("female") >female</option>
</select>
#{
List<SelectListItem> lstOrderTypes = new List<SelectListItem>();
lstOrderTypes.Add(new SelectListItem {Value = "1", Text = "plan1" });
lstOrderTypes.Add(new SelectListItem {Value = "2", Text = "plan2" });
}
#functions {
public static string GetString(IHtmlContent content)
{
var writer = new System.IO.StringWriter();
content.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
}
#{
var x = GetString(Html.DisplayFor(model => model.OrderType));
}
<select>
#foreach (SelectListItem option in lstOrderTypes)
{
<option value="#option.Value" selected="#(option.Value == x)">#option.Text</option>
}
</select>

Refresh asp.net mvc page

I have some app on asp.net mvc.
And I am trying to create table filter. Page is very difficult, so i can't get data from JSON response. I am trying to get it via call action with params.
function refresh() {
var id = $("#list").val();
var params = { id: id };
$.get("/Home/Index", params, null, "json");
}
<select id="list" onchange="refresh()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<%foreach (var i in (IEnumerable<int>)ViewData["list"])
{ %>
<%=i %><br />
<%} %>
public ActionResult Index(int? id)
{
if (id == null)
id = 0;
ViewData["list"] = Enumerable.Range((int)id, 5).Select(i => i).ToList<int>();
return View();
}
But I don't see new data. What's wrong?
How I can refresh page?
PS I meen that i wanna go(redirect) from action A to action A(with param). I don't want reconstruct page on client side
You aren't doing anything with the result you retrieve with the get call. Also, since you're returning a view, you should set your data type to html.
$.get('/Home/Index', params, function(html) {
$('body').html(html);
},'html');
I'd note that I would probably only replace the section that gets updated. You can do this by using a partial view to hold just that section, then when you get the request via AJAX you can return just the partial view instead of the full view. The other thing that I would do is make the views strongly-typed to IEnumerable<int> and pass a model, instead of using view data.
View
<script type="text/javascript">
$(function() {
$('#list').change( function() {
var id = $("#list").val();
var params = { id: id };
$.get("/Home/Index", params, function(html) {
$('#listResults').replaceWith(html)
}, "html");
});
});
</script>
<select id="list">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<% Html.RenderPartial( "ListResults" ); %>
Partial View
<div id="listResults">
<%foreach (var i in Model)
{ %>
<%=i %><br />
<%} %>
</div>
Action
public ActionResult Index(int? id)
{
if (id == null)
id = 0;
var model = Enumerable.Range((int)id, 5).Select(i => i).ToList<int>();
if (this.Request.IsAjaxRequest())
{
return PartialView(model);
}
return View(model);
}
I see one problem in the code above:
The $.get() does not do anything when your request is complete(your data has been fetched from the server)
Instead of passing null there you should pass in a function with a parameter which is the data. Example:
$.get("/Home/Index"
, params,
function(data){
//do something with data.
//data is json object returned
}, "json");
in this function you can actually have your filter applied to the table

Resources