Program couldnt find the path Partial view - c#

I have a dropdownlist that when someone select some item in dropdown it need to be render partial and that partial loading some checkboxes.I trying to render partial but it keeps throwing not found error.I'm sure about path
Is it related with Html.Partial or Html.RenderPartial ?
My Controller:
[HttpGet]
public ActionResult SendCheckList(string input)
{
if (String.IsNullOrEmpty(input))
return null;
FormDetailViewModel model = new FormDetailViewModel();
int id =Convert.ToInt32(input);
ItemsRepository items = new ItemsRepository();
CheckListRepository checkListRep = new CheckListRepository();
CheckList checkList = db.CheckLists.FirstOrDefault(t =>
t.CheckListTypeId == id);
List<Item> İtems = db.Items.Where(t => t.ItemId ==
checkList.ItemId).ToList();
foreach (Item item in İtems)
{
İtemList.Add(new SelectListItem { Value =
item.ItemId.ToString(), Text = item.ItemDesc });
}
model.İtems = İtemList;
return PartialView
("~/Areas/User/Views/FormDetail/SendCheckList.cshtml", model);
}
My View:
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"
type="text/javascript"></script>
<script src="~/Content/js/open.js"></script>
#using (Html.BeginForm())
{
<table class="table table-hover">
<tr>
<td>
#Html.DisplayNameFor(model => model.FormDetail.CheckListType)
</td>
<td>
#Html.DropDownListFor(model => model.FormDetail.CheckListTypeId,
Model.checkLists, new { #id = "Selection", #class = "drop-open"})
</td>
</tr>
Js/Jquery:
$(document).ready(function () {
$('#Selection').on('change', function () {
$('#results').load('#Html.RenderPartial("~/Areas/User/Views/FormDetail/
SendCheckList.cshtml")')
});
});

The following code works for me. You need to make some changes in the JQuery.
public ActionResult SendCheckList(string input)
{
---
---
---
return PartialView("~~/Areas/User/Views/FormDetail/SendCheckList.cshtml", mode);
}
JQuery
$(document).ready(function () {
$('#Selection').on('change', function () {
var obj = {};
obj.parameter = parameter;
$.ajax({
url: '/ControllerName/SendCheckList',
data: JSON.stringify(obj),
contentType: 'application/json; charset=utf-8',
cache: false,
type: 'POST',
datatype: 'json',
async: false
})
.success(function (data) {
$("#DivID").html(data);
});
});
);

Related

asp.net Razor Pages - Update select list based on the selection of another select list

I want to update a select list when the user selects a value in another select list. I've managed to get the first select list to call a get (or post) method on the model with a parameter, and can update the underlying data. But the second select list never shows the new values.
I'm not very experienced with asp.net, so what am I doing wrong?
Code below
.cshtml
<div>
<form method="post">
<select id="departureStation" asp-items="Model.DepartureStations" onchange="getDestinationStations()"></select>
<select id="destinationStation" asp-items="Model.DestinationStations"></select>
</form>
</div>
#section Scripts {
<script type="text/javascript">
function getDestinationStations() {
var selectedDepartureStationID = $("#departureStation").find(":selected").val();
console.log("selectedDepartureStationID = " + selectedDepartureStationID);
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
console.log("success - " + result);
},
error: function() {
console.log("failure");
}
})
}
</script>
}
.cs
public List<SelectListItem> DestinationStations
{
get
{
if (this._selectedDepartureStationID == -1)
return new List<SelectListItem>();
List<Models.Station> stations = new List<Models.Station>();
List<Models.RouteSegment> routeSegments = this._context.RouteSegments.Where(x => x.StationID == this._selectedDepartureStationID).ToList();
foreach (Models.RouteSegment routeSegment in routeSegments.DistinctBy(x => x.RouteID))
{
List<Models.RouteSegment> routeSegments2 = this._context.RouteSegments.Where(x => x.RouteID == routeSegment.RouteID).Include(x => x.Station).ToList();
stations.AddRange(routeSegments2.Select(x => x.Station));
}
return new List<SelectListItem>(stations.Distinct().ToList().Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList());
}
}
public IndexModel(MyViewContext context)
{
this._context = context;
}
public void OnGet()
{
this.DepartureStations = this._context.Stations.Select(x => new SelectListItem { Value = x.StationID.ToString(), Text = x.StationName }).ToList();
}
public IActionResult OnGetDeparture(int selectedDepartureStationID)
{
this._selectedDepartureStationID = selectedDepartureStationID;
return Page();
}
Whenever your #departureStation select changes, your code will call getDestinationStations javascript code. Inside that function you are sending a request to your backend server to receive possible destination stations if I understood correctly. What you need to do here is when ajax request successes, add options dynamically based on your returned array or data.
I am assuming your "/Index?handler=Departure" returns a JSON like:
[
{
id: 1,
name: "station1"
},
{
id: 2,
name: "station2"
}
]
Check if code below works.
$.ajax({
type: "GET",
url: "/Index?handler=Departure",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: {
selectedDepartureStationID: selectedDepartureStationID
},
success: function(result) {
let destinationStationSelect = $('#destinationStationSelect');
let optionTemplate = $('<option></option>');
$.each(result, (index, element) => {
let option = optionTemplate.clone();
option.append(element.name);
option.attr('value', element.id);
destinationStationSelect.append(option);
});
},
error: function() {
console.log("failure");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

ajax post does not return view data

I am using ajax post to call controller method DeviceData(). It does not return view data.
When I try to debug the code ,values are assigned to viewBag both in controller.cs and .cshtml but browser displays no data. Code does not return any error. After ajax call it only shows patientDDL.
I need to display "deviceName date etc.." which I assigned in viewBag.
This is my code:
DeviceData.cshtml
#model Hospital.Models.DeviceModel
<div class="row">
<div class="col-md-12">
<div id="pdf" class="pull-left">
<table>
<tr>
<td class="blue-bgcolor">Patient List : </td>
<td>
#Html.DropDownList("FromJson", new SelectList(Enumerable.Empty <SelectListItem>()),"select",
new { Class = "form-control", onchange = "SelectedIndexChanged()" })
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="row">
<table class="table valign-middle">
<tbody>
<tr>
<td>Device Name</td>
<td>#ViewBag.deviceName</td>
</tr>
<tr>
<td>DateTime</td>
<td>#ViewBag.date</td>
</tr>
<tr>
<td>SPO2</td>
<td>#ViewBag.spo2</td>
</tr>
<tr>
<td>PR</td>
<td>#ViewBag.pr</td>
</tr>
</tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "PatinetDDl",
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: JSON,
success: function(result) {
$(result).each(function() {
$("#FromJson").append($("<option></option>").val(this.Value).html(this.Text));
});
},
error: function(data) {}
});
});
</script>
<script type="text/javascript">
function SelectedIndexChanged() {
var pid = $("#FromJson").val();
alert(pid);
$.ajax({
url: '/Data/DeviceData',
type: 'POST',
datatype: 'json',
//contentType: 'application/json',
data: { pid: +pid },
success: function (result) { },
error: function () { alert("Whooaaa! Something went wrong..") },
});
}
</script>
Datacontroller.cs
public JsonResult PatinetDDl()
{
Common.DBConnect.fnconchk(con);
DataTable dtpatient = new DataTable();
string query = "";
query = "select Preg_id,P_Name from Patient_Reg";
SqlCommand cmd2 = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd2);
da.Fill(dtpatient);
List<SelectListItem> ObjList = new List<SelectListItem>();
foreach (DataRow row in dtpatient.Rows)
{
ObjList.Add(new SelectListItem()
{
Text = row["P_Name"].ToString(),
Value = row["Preg_id"].ToString()
});
}
var jsonData = ObjList;
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult DeviceData()
{
DeviceModel obj = new DeviceModel();
return View(obj);
}
[HttpPost]
public ActionResult DeviceData(string pid)
{
DeviceModel obj = new DeviceModel();
DataTable dt = new DataTable();
Common.DBConnect.fnconchk(con);
if (pid != null)
{
string query = "";
query = " select D_Name,Date_Time,D_Value1 from readings where pid='" + pid;
SqlCommand cmd2 = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd2);
da.Fill(dt);
ViewBag.deviceName = dt.Rows[0]["D_Name"].ToString();
ViewBag.date = dt.Rows[0]["Date_Time"].ToString();
ViewBag.spo2 = dt.Rows[0]["D_Value1"].ToString();
ViewBag.pr = dt.Rows[0]["D_Value2"].ToString();
}
return View(obj);
}
Many things you want to change to get the desire output.
First
make a partial view name _deviceInfo.cshtml
<table class="table valign-middle">
<tbody>
<tr>
<td>Device Name</td>
<td>#ViewBag.deviceName</td>
</tr>
<tr>
<td>DateTime</td>
<td>#ViewBag.date</td>
</tr>
<tr>
<td>SPO2</td>
<td>#ViewBag.spo2</td>
</tr>
<tr>
<td>PR</td>
<td>#ViewBag.pr</td>
</tr>
</tbody>
</table>
Second
Changing in your controller action method
[HttpPost]
public PartialViewResult DeviceData(string pid)
{
DeviceModel obj = new DeviceModel();
DataTable dt = new DataTable();
Common.DBConnect.fnconchk(con);
if (pid != null)
{
string query = "";
query = " select D_Name,Date_Time,D_Value1 from readings where pid='" + pid;
SqlCommand cmd2 = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd2);
da.Fill(dt);
ViewBag.deviceName = dt.Rows[0]["D_Name"].ToString();
ViewBag.date = dt.Rows[0]["Date_Time"].ToString();
ViewBag.spo2 = dt.Rows[0]["D_Value1"].ToString();
ViewBag.pr = dt.Rows[0]["D_Value2"].ToString();
}
return PartialView(obj);
}
Third
Ajax Method in DeviceData.cshtml
#model Hospital.Models.DeviceModel
<div class="row">
<div class="col-md-12">
<div id="pdf" class="pull-left">
<table>
<tr>
<td class="blue-bgcolor">Patient List : </td>
<td>
#Html.DropDownList("FromJson", new SelectList(Enumerable.Empty <SelectListItem>()),"select",
new { Class = "form-control", onchange = "SelectedIndexChanged()" })
</td>
</tr>
</table>
</div>
</div>
</div>
<div class="row" id="device-data">
</div>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "PatinetDDl",
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: JSON,
success: function(result) {
$(result).each(function() {
$("#FromJson").append($("<option></option>").val(this.Value).html(this.Text));
});
},
error: function(data) {}
});
});
</script>
<script type="text/javascript">
function SelectedIndexChanged() {
var pid = $("#FromJson").val();
alert(pid);
$.ajax({
url: '/Data/DeviceData',
type: 'POST',
datatype: 'html',
//contentType: 'application/json',
data: { pid: +pid },
success: function (result) {
$('#device-data').html(result);
},
error: function () { alert("Whooaaa! Something went wrong..") },
});
}
</script>
Hope it will work for you :)
The Problem is you return a view by action result (html) but you have used data type json in your second ajax script.
Edit SelectedIndexChanged like this :
function SelectedIndexChanged() {
var pid = $("#FromJson").val();
alert(pid);
$.ajax({
url: '/Data/DeviceData',
type: 'POST',
datatype: 'html',
//contentType: 'application/json',
data: { pid: +pid },
success: function (data) {
$('#placeHolder').html(data);
},
error: function () { alert("Whooaaa! Something went wrong..") },
});
}
Don't forget to add placeHolder element where ever you want to show the DeviceData:
<div id="#placeHolder"></div>

Values from Json for Jquery autocomplete

I'm a fairly new to JQuery, Json, and MVC. I am trying to a get the autocomplete to work in a text-box (with a drop-down). This is for a parameter value selection used in a web report. The data-table values are in the model called 'BSNList'. THen in the .cshtml View, the BSN text values have to be put to a var for the jquery function to run the autocomplete - I have it working with a inline list to test the autocomplete. But, I can't get the BSNList values to work in the jquery script- even trying with a JsonConvert.SerializeObject here is my code
birthCertificateModel.BSNList = new SelectList(_jobsParamData.AsDataView(), "JobId", "BSN");
birthCertificateModel.JSONresult = JsonConvert.SerializeObject(_jobsParamData);
return View(birthCertificateModel);
<div class="col-md-2">
#*<div class="ui-widget">*#
<label for="tags">BSNs: </label>
<input id="tags" class="ui-autocomplete-input" name="tags">
#*</div>*#
#Html.LabelFor(m => m.BSNName, ReportCaptions.BSN) <br />
#Html.ListBoxFor(m => m.BSNName,
Model.BSNList,
new { #class = "ListBox", size = 8 })
</div>
<script type="text/javascript">
var jsonBSNList;
jsonBSNList = #Model.BSNList.DataTextField;
$(document).ready(function () {
$(function () {
$("#tags").autocomplete({
source: jsonBSNList
});
});
});
`
Figured this out - here is my controller , html and script - I think the ajax is where I stumbled first.
[HttpPost]
public JsonResult SerialNumberLookup(string serialNumberString)
{
using (SqlConnection conn = new SqlConnection(this.connstr))
{
List<string> serialNumberList = new List<string>();
using (SqlCommand cmd =
new SqlCommand(BuildJobStatusModel.LookupSQLSelect, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#SearchText", serialNumberString);
SqlDataReader sqlDataReader = cmd.ExecuteReader();
while (sqlDataReader.Read())
{
serialNumberList.Add(sqlDataReader["SerialNumber"].ToString());
}
return this.Json(serialNumberList, JsonRequestBehavior.AllowGet);
}
}
<br />
#Html.LabelFor(model => model.SelectedSerialNumber, ReportCaptions.SerialNumber + " Look-up:")
#Html.TextBoxFor(model => model.SelectedSerialNumber, htmlAttributes: new { #id = "autocompleteSerialNumber" })
<br />
$("#autocompleteSerialNumber").autocomplete(
{
minLength: minSearchLen,
source: function (request, response) {
$.ajax({
url: "/Reports/SerialNumberLookup",
type: "POST",
// contentType: "application/json; charset=utf-8",
dataType: "json",
data: { SerialNumberString: request.term },
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
value: item
};
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
})
}
});

Get selectedIndex of dropdown using c# (Razor)

Is it possible to get the selectedIndex of a dropdown in a view using C# (Razor). For example, can I fill a second dropdown based off the selectedIndex of another dropdown using Razor?
#model ViewModel
<select id="dropdown1">
//Options
</select>
<select id="dropdown2">
//Options
</select>
#if(//The selectedIndex of dropdown1 == 4)
{
//Fill dropdown 2 from model
}
When using Javascript, I am a little off as well:
<script>
if (dropdown1.selectedIndex === 3)
{
#foreach (var item in Model)
{
}
}
</script>
You can do it using a ajax call when the first dropdown changes:
<script type="text/javascript">
function getDropDown2Data(id) {
$.ajax({
url: '#Url.Action("GetDropDown2Data", "YourController")',
data: { Id: id },
dataType: "json",
type: "POST",
success: function (data) {
var items = "";
$.each(data, function (i, item) {
items += "<option value=\"" + item.Name + "\">" + item.Id + "</option>";
});
$("#dropDown2").html(items);
}
});
}
$(document).ready(function () {
$("#dropDown2").change(function () {
var id = $("#dropDown2").val();
getDropDown2Data(id);
});
});
</script>
#Html.DropDownListFor(x => x.Id, new SelectList(Model.Model1, "Id", "Name"), "Select")
#Html.DropDownListFor(x => x.Id, new SelectList(Model.Model2, "Id", "Name"), "Select")
And you action:
[HttpPost]
public ActionResult GetDropDown2Data(id id)
{
//Here you get your data, ie Model2
return Json(Model2, JsonRequestBehavior.AllowGet);
}

drop down list refresh in razor

I have a drop down list which represent states and according to selected state, I need to refresh City drop down list which represent the cities in the selected state. How can I refresh the city drop down ?
Here is my code :
public class AccountController : Controller
{
public static List<SelectListItem> StateListItem()
{
var stateList = new List<SeraydarBL.Accounts.State>();
var selectListItems = new List<SelectListItem>();
stateList = SeraydarBL.Accounts.SelectStates();
foreach (var state in stateList)
{
var selectListItem = new SelectListItem();
selectListItem.Text = state.name;
selectListItem.Value = state.id.ToString();
selectListItems.Add(selectListItem);
}
return selectListItems;
}
}
here is the razor :
#using (Html.BeginForm())
{
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
//-------------------------------------------------------
var stateList = new List<SelectListItem>();
stateList = AccountController.StateListItem();
}
#Html.LabelFor(model => model.StateId)
#Html.DropDownListFor(model => model.StateId, stateList, " Select your State ...")
#Html.ValidationMessageFor(m => m.StateId)
#*HERE MUST BE THE DROP DOWN LIST OF CITIES*#
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
<script>
$('#StateId').change(function () {
});
</script>
}
You can achieve this using jquery ajax call.
<script type="text/javascript">
$(document).ready(function () {
//Dropdownlist Selectedchange event
$("#StateId").change(function () {
$("#CityId").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCity")',
dataType: 'json',
data: { id: $("#StateId").val() },
success: function (cities) {
$.each(cities, function (i, city) {
$("#CityId").append('<option value="' + city.Value + '">' +``});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
refer few articles
http://www.codeproject.com/Articles/730953/Cascading-Dropdown-List-With-MVC-LINQ-to-SQL-and-A
http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-cascading-dropdownlist-in-mvc-4-using-razor/

Categories