why parameter value null when second controller loads in mvc, c# - c#

Note : I'm new to MVC
In my case it has two views and two controllers.I am passing selected item value to the the second controller from first view using ajax.passing is success.
but when second view appears , the value is null.Is this ajax problem or mvc. I can't understand.
this is my first controller and first view
public ActionResult First()
{
//get the location data
var Loc = getData("Location", "", "", "");
List<Firstdata> llc = new List<Firstdata>();
foreach (var val in Loc)
{
llc.Add(new Firstdata
{
Destination =val
});
}
ViewBag.Loc = llc;
return View();
}
first view
<div class="col-md-6 form-group">
<label>Destination</label>
<select class="form-control" id="destination">
#foreach (var item1 in #ViewBag.Loc)
{
<option>#item1.Destination</option>
}
</select>
</div>
<div class="clearfix"></div>
<div class="form-group">
<div class="btn" id="bud">
#Html.ActionLink("GO", "Check","Cruise")
</div>
</div>
ajax passing in first view
<script type="text/javascript">
$("#bud a").click(function () {
var destination = $("#destination").val();
$.ajax({
url: '#Url.Action("Check","Cruise")',
data: { 'destination': destination },
type: "POST",
dataType: "XML",
//contentType: "application/xml",
async: true,
success: function(data){
if (!data)
alert("no xml data returned");
else {
alert("success");
}
//location.href = "~/Views/Cruise/Check.cshtm";
}
});
});
</script>
this is my second controller
public ActionResult Check(string destination)
{
XElement rootele = XElement.Load(Server.MapPath("~/XmlFiles/CruiseData/cruiseprodutstwo.xml"));
var getneededData = rootele.Elements("CruiseProduct")
.Where(l => l.Element("Location").Value == destination)
.Select(s => s.Element("Name").Value);
List<Details> d = new List<Details>();
foreach(var itm in getneededData)
{
d.Add(new Details
{
cruiseName = itm
});
}
ViewBag.needed = d;
return View();
}
** In this point destination is not null and d(ViewBag.needed) is also not null.it shows the count
this is my second view
<div>
#foreach (var itme in #ViewBag.needed)
{
<h2>#itme</h2>
}
</div>
in here loop go through for #ViewBag.needed count and finally display null.no idea what is going.
please help me with this.

I think there is a routing problem there. If you are using default routing that is
routes.MapRoute(name:"Default",
url:"{controller}/{action}/{id}",
defaults:new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
then you need to chagne controller parameter name destination to id
as:
public ActionResult Check(string id)
{
and in JQuery call change it as
$.ajax({
url: '#Url.Action("Check","Cruise")',
data: { 'id': destination },
Or
you can add new route in RouteConfig.cs as
routes.MapRoute(name:"Default",
url:"{controller}/{action}/{destination}",
defaults:new { controller = "Cruise", action = "Check" }
);
For routing you can refer to http://www.niceonecode.com/Q-A/DotNet/MVC/routing-in-mvc-4/20190

Related

How can I show the price according to the selected option without refreshing the page with c#

I have not worked with Ajax so far and I want to show the price after selecting the desired option without refreshing the page.
<div class="form-group">
<label class="control-label">choice your Option</label>
<select>
#foreach (var item in Materials)
{
<option value="#item.Id">
#item.MaterialName #item.Panel
</option>
}
</select>
<span class="main-price ">#item.Price</span>
</div>
Lets see what we can do here for your case:
Assign an id to your select to hold the value that you will send your server and span to display the output from the server:
<div class="form-group">
<label class="control-label">choice your Option</label>
<select id="ddlMaterial">
#foreach (var item in Materials)
{
<option value="#item.Id">
#item.MaterialName #item.Panel
</option>
}
</select>
<span class="main-price" id="priceDisplay">#item.Price</span>
</div>
Now we define the AJAX call that will send the request to the server. This request will get the current id of the selected option and then covert it to a JSON string which is sent to the server for processing. The url is the action method which will be invoked on this call:
$(document).ready(function () {
$("#ddlMaterial").change( function (event) {
var id = $(this).val();
var json = {id : id};
$.ajax({
type: 'POST',
url: "#Url.Action("GetPrice", "Home")",
dataType : "json",
data: {"json": JSON.stringify(json)},
success: function(data) {
if(data.status=="true")
{
$("#priceDisplay").text(data.price);
}
else
{
alert('Some error');
}
},
error: function(data) {
alert('Some error');
window.location.reload();
}
});
});
});
And finally your Controller action method will be:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult GetPrice(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
var id = Convert.ToInt32(jsondata["id"]);
//Get the price based on your id from DB or API call
var getMyPrice=GetPrice(id);
return Json(new {status="true", price= getMyPrice});
}

Image list not displaying with ajax call in asp.net mvc

My images list not displaying when i call images with ajax call . on page load code work perfectly but on ajax call it did not display any images list my code is.
The view markup is:
<script>
$(document).ready(function () {
$(".yesterdayfilter").click(function () {
var username = $("#users-ddl option:selected").text();
alert(username);
$.ajax({
type: 'Post',
url: "/Home/index",
dataType: 'image/jpg',
data: {
Username: username,
},
success: function (status) {
console.log('Send');
},
error: function () {
console.log('something went wrong - debug it!');
}
});
});
});
</script>
The code where image display in view:
<div class="flex items-center" data-toggle="modal" data-target="#superlarge-modal-size-
preview">
#{
if (Session["recentscreenshotss"] != null)
{
var screenshotslist =
(List<ezilineezitaskernew.Models.sp_getrecentscreenshots_Result>)Session["recentscreenshotss"];
if (screenshotslist != null)
{
foreach (var item in screenshotslist)
{
<div class="col-span-6 sm:col-span-12 xl:col-span-12 mt-8">
<div class="flex-justifiy flex-wrap">
<div class="w-24 h-24 relative image-fit mb-5 mr-5 cursor-pointer zoom-in">
<button value="#item.Image" data-toggle="modal" data-target="#basic-modal-preview" class="testing"><img class="rounded-md" alt="Midone Tailwind HTML Admin Template" src="#item.Image"></button>
<div class="tooltip w-5 h-5 flex items-center justify-center absolute rounded-full text-white bg-theme-6 right-0 top-0 -mr-2 -mt-2 tooltipstered"> <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="feather feather-x w-4 h-4"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg> </div>
</div>
</div>
</div>
}
}
}
}
</div>
The controller:
[HttpPost]
public ActionResult Index(string Username)
{
GetOffices();
SetLogo();
var Userid = dbcontext.USERS.Where(x => x.Username == Username).FirstOrDefault();
int UID = Userid.Id;
int companyid = Convert.ToInt32(Session["company-id"]);
var screenshotlist = dbcontext.sp_getrecentscreenshots(null, null, companyid).ToList();
int s_startId = screenshotlist[0].Id;
int s_lastId = s_startId + 6;
if (screenshotlist != null)
{
var screenshots = dbcontext.sp_getrecentscreenshots(s_startId, s_lastId,
companyid).ToList();
Session["recentscreenshotss"] = screenshots;
}
}
The code is fine . only issue is that it is not displaying images . the same code work when page load but not working with ajax call can anyone help me?
there is different solution to your problem:
solution 1:
On ajax success you can reload page with the Username as parameter
solution 2 :
.empty() and .append your <div> on ajax success with your <div> content
solution 3 :
The cleanest solution:
Put your <div> content in a partial view named for example Searchpartial.cshtml
Add an empty in your current view and give it the an id for example <div id="divSearch"></div>
and load it with your button as follow with GET:
$("#divSearch").empty()
$.get("/Home/Searchpartial", { Username: 'username' },
function (result) {
$("#divSearch").append(result);
}
);
In your controller need to call your partial view as follow:
[HttpGet]
public PartialViewResult Searchpartial(string Username)
{
// your code
return PartialView("Searchpartial");
}
I see that your controller HTTP Post is pointing to Index in your ajax I notice it was index be careful for case sensitive.

Populate a textbox based on selected value from dropdown using ASP.NET Core MVC

I am using ASP.NET Core 3.1 MVC to create a page with a form. The form has a dropdown and a textbox. The dropdown is populated with values from the database. The textbox will populate with a value from the same table and the dropdown, based on the selected dropdown value. My goal is to call a function from my controller inside of my view, is that possible?
My cshtml file:
<form method="post" asp-controller="Index" asp-action="Index" role="form">
<div class="form-group">
<select id="fileName" asp-items="#(new SelectList(ViewBag.message, "ID", "fileName"))" onchange="getUploadedFile()"></select>
<input />
</div>
</form>
My Model
public class myFiles
{
public int ID {get; set;}
public string fileName {get; set;}
public string uploadedFile {get; set;}
}
My controller has a function named GetUploadedFile() which runs a query to the database that returns the file name based on the ID. I originally thought I could reference the GetUploadedFile through my view(cshtml file) by adding the onchange handler and setting it as onchange="GetUploadedFile()". I have also tried to do an ajax call to get the UploadedFile.
My goal is to call a function from my controller inside of my view, is that possible?
Do you mean you want to add the myfiles' uploadfile value according to the dropdownlist selected value in the onchange getUploadedFile jquery method? If this is your requirement, I suggest you could try to use ajax to achieve your requirement.
You could write the ajax to post request to the mvc action, then you could get the value and set the result to the textbox.
Details, you could refer to below codes:
<form method="post" asp-controller="home" asp-action="Index" role="form">
<div class="form-group">
<input id="uploadedFile" type="text" class="form-control" />
<select id="fileName" asp-items="#(new SelectList(ViewBag.message, "ID", "fileName"))" onchange="getUploadedFile(this)"></select>
</div>
</form>
<script>
function getUploadedFile(Sle) {
$.ajax({
url: "/Home/GetUploadfileName",
data: { "FileID": Sle.value} ,
type: "Post",
dataType: "text",
success: function (data) {
console.log(data);
$("#uploadedFile").val(data);
},
error: function (data) {
alert(data);
}
});
}
</script>
Action method:
private List<myFiles> myfiletestdata = new List<myFiles>() {
new myFiles(){ ID=1, fileName="test1", uploadedFile="testuploadfile" },
new myFiles(){ ID=2, fileName="test2", uploadedFile="testuploadfile2" },
new myFiles(){ ID=3, fileName="test3", uploadedFile="testuploadfile3" },
};
[HttpPost]
public IActionResult GetUploadfileName(int FileID) {
//get the filename result accoding to ID
var result = myfiletestdata.Where(x=>x.ID== FileID).First();
return Ok(result.uploadedFile);
}
Result:
If I understand correctly, you just want to get the file name from the database when a value from the dropdown is selected.
What errors did you get when you tried the ajax call??
In your cshtml file, you can have something like this:
<script>
function getUploadedFile() {
var id = $('#fileName option:selected').val();
$.getJSON('/ControllerName/GetUploadedFile', { id: id }, function (result) {
var file = result.fileName;
.... do whatever with the result
to set value of the textbox:
$('#textBoxId').text(file);
});
}
</script>
Instead of getJSON, you could use ajax:
<script>
function getUploadedFile() {
var id = $('#fileName option:selected').val();
$.ajax({
url: 'ControllerName/GetUploadedFile',
type: 'GET',
dataType: 'json',
data: {
'id': id
}
})
.done(function (result) {
if (!result.errored) {
var file = result.fileName;
}
else {
}
});
}
</script>
Then in your controller, if you are not submitting the form and just want to update the value of the textbox, then it can just be:
[HttpGet]
public async Task<IActionResult> GetUploadedFile(int id)
{
Sample code:
var file = await GetFileFromDb(id);
return Json(new { fileName = file });
}
Also, you should consider using ViewModels instead of ViewBag.

Using ajax to update fields in a view based off of dropdown onchange with a method in the DAL

I have a view that has a dropdown that is generated by a linq statement when the view is populated.
<div class="form-group">
#Html.LabelFor(m => m.OrderID, "Order ID")
<div>
#Html.DropDownListFor(m => m.OrderID, Model.Orders, "Select Order ID",
new { #id = "orderDropdown" })
</div>
</div>
I have 2 other fields in the view that need to be updated with the data retrieved from the database.
<div class="form-group">
#Html.Label("Final Weight")
<div id="finalWeight">
#Html.DisplayFor(m => m.FinalWeight)
</div>
</div>
<div class="form-group">
#Html.Label("Initial Weight")
<div id="initialWeight">
#Html.DisplayFor(m => m.InitialWeight)
</div>
</div>
This is the ajax that I got from the link below:
<script>
$("#orderDropdown").change(function (event) {
$.ajax({
url:"???" + $(this).val(),/* not sure what to use*/
data: { id: $(this).val()},
cache: false,
type: "GET",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
$("#divinitialWeight").html(data);
}
});
});
Here is the controller code
[HttpGet]
[OpenAction]
public async Task<float> GetInitialWeight(int sid)
{
var initialWeight = await Manager.FindInitialFilterWeightBySID(sid);
return initialWeight.MeanWeight;
}
The method is in a Data Access Layer that is only referenced in the main project. The way I would call it in the controller would be like below and pass it the orderId :
Entities.Manager.FindInitialWeight(orderId);
Entities.Manager.FindFinalWeight(orderId);
I came across this SO question and it's close to what I need but the only issue is the url: because the data retrieval method is not in my controller...it is in the data access layer that is only a reference. Also the orderId is being passed as a parameter.
How can I call that method from ajax and pass it the orderId from the url: of the ajax call?
You can call the controller method from JQuery like this
if the JQuery code is within the razor view
url: '#Url.Action("GetInitialWeight")',
data: { sid: $(this).val()},
I actually had to create a GET method in my controller that contacted the DAL with the passed parameter from the javascript
[HttpGet]
[OpenAction]
public async Task<ActionResult> GetInitialWeight(int sid)
{
var initialWeight = await Manager.FindInitialFilterWeightBySID(sid);
return Json(new { initialWeight.MeanWeight }, JsonRequestBehavior.AllowGet);
}
Then change the javascript as such
<script>
$("#sidDropdown").change(function (event) {
var url = "/Controller/GetInitialWeight/";
var data = { sid: $(this).val() };
var dataType = "json";
$.get(
url,
data,
function (response) {
$("div#initialWeight").text(response.MeanWeight)
console.log(response.MeanWeight);
}, dataType);
});

Post a form with ajax and display error in a div in case of error

In the code below, I have a form with some informations about an employee. I'd like feel in the password and post. If the password is correct the user is redirected to /Dashboard that it's ok.
When the password is wrong, I'd like show the error (_ErrorPartial) in MyError div and still see the form. I'd like see the form and the message in the div (MyError). With the code below, when the password is wrong, I see the error message but on a blank page and not a page with the layout + the form + the error message
Any idea ?
Thanks,
My page :
#model MyApp.EmployeeModel
<script type="text/javascript">
$(document).ready(function () {
$(".").click(function () {
$.ajax({
url: '/Account/Login',
type: "Post",
data: $('#MyForm').serialize(),
success: function (result) {
alert('Im here');
$("#MyError").html(result);
//Here is code to detect error or not but removed
}
});
});
});
</script>
<div id="MyError"></div>
#using (Html.BeginForm("Login", "Account", FormMethod.Post, new { id = "MyForm" }))
{
#Html.AntiForgeryToken()
<div>
#Html.LabelFor( m => m.FirstName)
<div>
#Html.HiddenFor(model => model.Username)
#Html.LabelFor( m => m.Password)
#Html.PasswordFor(m => m.Password)
<input type="submit" class="jqClick" />
</div>
</div>
}
Controller :
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(EmployeeModel employeeModel)
{
var Errors = new List<string>();
var employee = .... //Get employee from DB
if (employee == null)
{
Errors.Add("Employee trouble");
return PartialView("_ErrorPartial", Errors.AsEnumerable());
}
return RedirectToAction("Index", "Dashboard");
}
My _ErrorPartial view :
#model IEnumerable<string>
<div id="DisplayError">
#{ var error = string.Empty; }
#foreach (var err in Model){
error += err + "<br>";
}
#Html.Raw(error)
</div>
You have to make some changes to your javascript code. First of all, replace jQuery selector $(".") with specific one, like $(".jqClick"). Second of all, never hardcode urls like /Account/Login in your code, use UrlHelper for that. And the third thing is, you have to prevent a default behavior of the submit button. See the changes:
$(document).ready(function () {
$(".jqClick").click(function (e) {
e.preventDefault();
$.ajax({
url: '#Url.Action("Login", "Account")',
type: "Post",
data: $('#MyForm').serialize(),
success: function (result) {
alert('Im here');
if (result.redirectUrl)
window.location.href = result.redirectUrl;
else
$("#MyError").html(result);
//Here is code to detect error or not but removed
}
});
});
});
Also you need to change the Login action a little in order to make a redirect if a login is success:
public ActionResult Login(EmployeeModel employeeModel)
{
var Errors = new List<string>();
var employee = .... //Get employee from DB
if (employee == null)
{
Errors.Add("Employee trouble");
return PartialView("_ErrorPartial", Errors.AsEnumerable());
}
return Json(new { redirectUrl = Url.Action("Index", "Dashboard") });
}
The probable error that you throw from the server side, won't appear in success function. Instead you should have below
error:function(response)
{
//your code here
}
Simply throw exception from the controller.

Categories

Resources