The application is in .Net framework 3.5 and MVC framework 2.0 for .Net framework 3.5. I have a view which in $.post passes parameters. I also need that $.post , passes model values to controller.
In the view below , how do I pass model in the $.post function, so that the controller gets the value of the Textbox. I need the button and not submit button.
The view is:
<div>
<label for ="Name"> Name</label> <%=#Html.TextBoxFor(m => m.Name) %>
<select id ="prod" style ="width:150px">
<option value ="GL">GL</option>
<option value = "Property"> Property</option>
<option value = "Package">Package</option>
<option value = "Island">Island</option>
</select>
<input type="button" id="btnPost" value = "GetValue" />
</div>
<script src="/Scripts/jquery-1.4.1.min.js" type ="text/javascript"></script>
<script type ="text/javascript" >
$(function() {
$("#btnPost").click(function() {
alert("here" + $("#prod").val());
$.post("/Transfer/DisplayText", { "str1": $("#prod").val()},
function(data) {
alert("success");
});
});
});
Th controller is:
[HttpPost]
public ActionResult DisplayText(string
str1,TestPost_AjaxMVC.ViewModels.TransferViewModel model)
{
string str2 = str1;
return View("Transfer");
}
The model is :
public class TransferViewModel
{
public string Name { get; set; }
}
I think everything is ok in your code just replace
$.post
to $.get
Because you are returning a view from your controller also use Url.action
like below because it may not work when you publish the project
$.get('<%=Url.Action("DisplayText","Transfer")%>', { str1: $("#prod").val()},
function(data) {
alert("success");
});
You should remove double quote from str1.Let me know if it does not work.
JSON.stringify the model and send it as part of data and let MVC use JSON Model Binding
$(function() {
$("#btnPost").click(function() {
var TransferViewModel={};
TransferViewModel.Name="SomeData";
var postData={};
postData.str1=$("#prod").val();
postData.model=TransferViewModel;
$.ajax({
url:"/Transfer/DisplayText",
type:"POST",
data:JSON.stringify(postData),
contentType:"application/json; charset=utf-8",
success: function(){
}
});
});
});
Related
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});
}
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.
Hello guys i hope you all are doing great, so i am working on a project with my buddy but we both are intermediate programmers and stuck into a place so i need your help...
the problem is I'm stuck in a certain code which is for "search the dish":
ShowAll list page
After selecting value from a combo box
it's doing post back from java script method as you can see in the picture but i think my code is incomplete because i can't get value from database i is showing the list on my "ShowAll page" but when i choose a value from combo box it doesn't show anything..
ActionResult Code
public ActionResult ShowAll()
{
var a = from tb in me.RecipeTables select tb;
return View(a.ToList());
}
[HttpPost]
public ActionResult ShowAll(string searchDish)
{
var k = me.RecipeTables.Where(l => l.recipeName == searchDish);
return View(k);
}
View Code wit java script function
<html>
<script type="text/javascript">
function SelectedIndexChanged()
{
this.myForm.submit();
}
</script>
<%using (Html.BeginForm("ShowAll", "RecipeView", FormMethod.Post, new { id = "myForm", name = "myForm", enctype="multipart/form-data"}))
%>
<p>
<%: Html.ActionLink("Create New", "Create") %>
<select id="searchDish" name="searchDish" onchange="SelectedIndexChanged()">
<option value="0">Select any</option>
<option value="1">biryani</option>
<option value="2">fried rice</option>
<option value="3">Nihari</option>
<option value="4">Tikka</option>
</select>
</p>
need help!!! thanks in advance
For this functionality you need to add Ajax call on OnChange of searchDish
but you need to add in your code for return result
Note : for this functionality you need to add JQuery libraries in your code.
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
Ajax Call :
$('#searchDish').change(function () {
var vid = $("#searchDish").val();
$.ajax({
url: "/RecipeView/ShowAll?id=" + vid,
type: "POST",
dataType: "html",
data: 'json',
async: false,
success: function (data) {
$('#divLanguage').html(data);
}
});
});
Cheers !!
the problem was with the i was sending string value in constructor and retrieving in numbers so i just changed it to and you can even do this that don't give any value it will work.. :)
I am new to both AngularJs and MVC. I am trying to get related records for a company when the company is selected in a dropdown list using AngularJS and MVC. I am populating the dropdown list, but when a company is selected, the event to get related records never fires. Here is my Angular Controller:
myApp.controller("CompanyController",
function($scope, $timeout, companyService)
{
getCompanies();
function getCompanies() {
companyService.getCompanies()
.success(function (data) {
$scope.companies = data;
})
.error(function (error) {
$scope.status = 'Unable to load customer data: ' + error.message;
});
};
$scope.getCurrentModules = function(){
companyId = $scope.company;
companyService.getCurrentModules(companyId)
.success(function (data){
$scope.data =data;
});
}
});
Here is my Angular Service:
angular.module('dashboardManagement')
.service('companyService', [
'$http', function ($http) {
this.getCompanies = function () {
return $http.get('/Home/GetAllCompanies');
};
this.getCurrentModules = function (id) {
return $http.get('/Home/GetCurrentModules?id=' + id);
};
}
]);
Here is my MVC View:
<td>
Please Select an Operator:<br />
<br />
<div id="companyContainer">
<div ng-controller="CompanyController">
<select id="CompanySelector" data-ng-model="company" data-ng-change="getCurrentModules()">
<option ng-repeat="company in companies" value="{{company.CompanyID}}">{{company.vchCompanyName}}</option>
</select>
<br />
You selected: {{company}}
</div>
</div>
</td>
Here is my MVC Controller:
[System.Web.Http.HttpPost]
public JsonResult GetCurrentModules(int companyId)
{
// throw new NotImplementedException();
var modules = this._operatorDashboardRepository.GetWithStoredProcedure("scGetDashboardModulesByWidgetID #WidgetID", "companyId");
var moduleList = modules.OrderBy(module => module.vchRankingWidgetModuleHeaderText);
return Json(moduleList, JsonRequestBehavior.AllowGet);
}
Can anyone tell me what I am doing wrong? I placed a break in the MVC Controller to see if the "GetCurrentModules" ever fires, but it does not. Any assistance is greatly appreciated.
Option 1
Change your getCurrentModules method to use $http.post instead of $http.get. Also make sure your parameter names match
return $http.post('/Home/GetCurrentModules?companyId=' + id);
public JsonResult GetCurrentModules(int companyId)
Option 2
Change your JsonResult to allow HttpGet
[System.Web.Http.HttpGet]
public JsonResult GetCurrentModules(int companyId)
again make sure parameter names match
I am having a tough time figuring out how to do this. I have added a search box to the main page of my site. The site has various products you can buy divided into categories. When you click one of the categories(for instance Candles and Scents), it takes you to /Home/Products/candles-scents. Now I have created new methods in my controller and model which correctly do the search. My search function is basically duplicating my "product categories" function, only the sql query is modified. So I want the site to go to the products page again, just like for a specific category: /Home/Products/"search". I'm not sure if I should wrap my search box in a form or if there is a better way. Right now I am trying jquery ajax, but of course the page is not getting redirected.
Here is my search box html:
<input type="text" class="search" placeholder="search" onfocus="this.placeholder = ''" onblur="this.placeholder = 'search'"/>
And here is my jquery:
$(".search").keypress(function (event) {
var searchString = $(this).val();
console.log(searchString);
console.log("blah");
if (event.which == 13) {
$.ajax({
url: '#Url.Action("_search", "Home")',
data: {
search: searchString
}
})
}
});
And here is the _search function in the controller:
public ActionResult _search(string search)
{
// get the model
List<ProductModel> m = new List<ProductModel>();
m = ProductsModel.getProductsBySearch(search);
return View(m);
}
Then that function simply calls runs the sql query and returns a list of appropriate ProductModel's. I have the backend stuff figured out. I am just not sure how to correctly call my search from the front end.
Seems like you don't want Ajax here if you are returning a complete view.
Consider this javascript to do the redirection without a form:
$(".search").keypress(function (event) {
var searchString = $(this).val();
console.log(searchString);
console.log("blah");
if (event.which == 13) {
var searchUrl = '#Url.Action("_search", "Home")';
searchUrl += "/" + searchString;
window.location.href = searchUrl;
} // end if
});
Or, using a forms approach
<script type="text/javascript">
$(".search").keypress(function (event) {
var searchString = $(this).val();
console.log(searchString);
console.log("blah");
if (event.which == 13) {
$("#search-form").submit();
} // end if
});
</script>
<form id="search-form" method="post" action="#Url.Action("_search", "Home")">
<input type="text" class="search" name="search" placeholder="search" onfocus="this.placeholder = ''" onblur="this.placeholder = 'search'"/>
<input type="submit" value="Go" name="submit" />
</form>
The important piece I added was the name="search" attribute to your input. This tells the default MVC ModelBinder to find the HTML input element with a name matching your controller's action parameter (missing in your source).
You can use success function to prevent a page reload
$(".search").keyup(function (e) {
var searchString = $(this).val();
if (e.which == 13) {
$.ajax({
type: "POST",
url: '#Url.Action("_search", "Home")',
data: {
search: searchString
},
success: function () {
// do something here, like replace the html
}
});
}
});
One tip from conventions, use your action name like this
public ActionResult Search(string search)