I have this form-
#using (Html.BeginForm("SaveVideo", "Upload", FormMethod.Post, new { id = "form-upload", #Class = "form-horizontal", enctype = "multipart/form-data", onsubmit = "return tags()", genres = "return genres()" }))
{
}
where on form submit I will need to send strings seperated by comma.
<script type="text/javascript">
function genres() {
var genres = $('#input-genreautocomplete').val();
return genres;
}
function tags() {
var tags = $('#input-tagautocomplete').val();
return tags;
</script>
Now as an example genre would be like- 23,15,16,22,11 as same as tags is. It return me string seperated by comma.
Now I want to use these strings in my method SaveVideo . But I can't get these strings working as parameters. How Do I send these strings on method?
Autocompletes working like this-
<script type="text/javascript">
$(function () {
$('#input-tagautocomplete').tagsinput({
itemValue: 'Id',
itemText: 'TagName',
typeahead: {
source: function (term, process) {
items = [];
map = {};
idofitem = [];
var url = "#Url.Content("~/Upload/GetTagNames/")";
return $.getJSON(url, { term: term }, function (data) {
$.each(data, function (i, item) {
map[item] = item;
items.push(item.TagName);
});
return (items);
});
},
updater: function (item) {
var selected = map[item].Id;
$('#tag-value').val(selected);
return item;
}
}
});
});
</script>
Where updater is not working, though it's bootstrap's typeahead's extension.
I think you are a bit confused. Action parameters don't need to be specified in the BeginForm() helper. In fact, I don't think doing so makes any sense. Firstly, these inputs should be inside your form if they're not already:
#using (Html.BeginForm("SaveVideo", "Upload", FormMethod.Post, new { id = "form-upload", #Class = "form-horizontal", enctype = "multipart/form-data"}))
{
<input type="text" id="input-tagautocomplete" name="tags" />
<input type="text" id="input-genreautocomplete" name="genres" />
}
You could also create these using an HTML helper. The important thing is that they have a value specified for their name attribute.
Then you can just add parameters to your action method to match these names:
public ActionResult SaveVideo(string tags, string genres)
{
// do whatever you want with tags and genres
}
Related
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.
I'm trying to write CRUD operations using ajax. Here some code:
These are my View classes:
//PhotoSummary
#model PhotoAlbum.WEB.Models.PhotoViewModel
<div class="well">
<h3>
<strong>#Model.Name</strong>
<span class="pull-right label label-primary">#Model.AverageRaiting.ToString("# stars")</span>
</h3>
<span class="lead">#Model.Description</span>
#Html.DialogFormLink("Update", Url.Action("UpdatePhoto", new {photoId = #Model.PhotoId}), "Update Photo", #Model.PhotoId.ToString(), Url.Action("Photo"))
</div>
//Main View
#model PhotoAlbum.WEB.Models.PhotoListViewModel
#{
ViewBag.Title = "My Photos";
}
#foreach (var p in #Model.Photos)
{
<div id=#p.PhotoId>
#Html.Action("Photo", new {photo = p})
</div>
}
The sript:
$('.dialogLink').on('click', function () {
var element = $(this);
var dialogTitle = element.attr('data-dialog-title');
var updateTargetId = '#' + element.attr('data-update-target-id');
var updateUrl = element.attr('data-update-url');
var dialogId = 'uniqueName-' + Math.floor(Math.random() * 1000)
var dialogDiv = "<div id='" + dialogId + "'></div>";
$(dialogDiv).load(this.href, function () {
$(this).dialog({
modal: true,
resizable: false,
title: dialogTitle,
close: function () { $(this).empty(); },
buttons: {
"Save": function () {
// Manually submit the form
var form = $('form', this);
$(form).submit();
},
"Cancel": function () { $(this).dialog('close'); }
}
});
$.validator.unobtrusive.parse(this);
wireUpForm(this, updateTargetId, updateUrl);
});
return false;
});});
function wireUpForm(dialog, updateTargetId, updateUrl) {
$('form', dialog).submit(function () {
if (!$(this).valid())
return false;
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
$(dialog).dialog('close');
$(updateTargetId).load(updateUrl);
} else {
$(dialog).html(result);
$.validator.unobtrusive.parse(dialog);
wireUpForm(dialog, updateTargetId, updateUrl);
}
}
});
return false;
});
}
And here my Tag builder:
public static MvcHtmlString DialogFormLink(this HtmlHelper htmlHelper, string linkText, string dialogContentUrl,
string dialogTitle, string updateTargetId, string updateUrl)
{
TagBuilder builder = new TagBuilder("a");
builder.SetInnerText(linkText);
builder.Attributes.Add("href", dialogContentUrl);
builder.Attributes.Add("data-dialog-title", dialogTitle);
builder.Attributes.Add("data-update-target-id", updateTargetId);
builder.Attributes.Add("data-update-url", updateUrl);
builder.AddCssClass("dialogLink");
return new MvcHtmlString(builder.ToString());
}
So, I have major problem if the dialog was called twice without the calling page being refreshed:
it just redirects me to the action page.
The question is how to update #Html.Action without reloading the page?
Could anyone help me?
Your #foreach loop in the main view is generating a partial view for each Photo which in turn is creating a link with class="dialogLink".
Your script handles the click event of these links and replaces it with a new link with class="dialogLink". But the new link does not have a .click() handler so clicking on the new (replacement) link does not activate your script.
Instead you need to use event delegation to handle events for dynamically generated content using the .on() method (refer also here for more information on event delegation). Note also that your current use of $('.dialogLink').on('click', function () { is the equivalent of $('.dialogLink').click(function () { and is not using event delegation. It attaches a handler to elements that exist in the DOM at the time the page is loaded, not to elements that might be added in the future.
Change your html to
<div id="photos">
#foreach (var p in #Model.Photos)
{
<div class="photo">#Html.Action("Photo", new { photo = p })</div>
}
</div>
and then modify the script to
$('#photos').on('click', '.dialogLink', function() {
....
});
Side note: There is no real need to add an id=#p.PhotoId to the containing div element and you could use <div class="photo"> as per above, and then reference it by using var updateTargetId = $(this).closest('.photo'); and delete the builder.Attributes.Add("data-update-target-id", updateTargetId); line of code from your DialogFormLink() method
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
I need to be able to populate data into a <div> or some other sort of section from an object after the corresponding string has been selected from a drop down list (lazy loading).
When a chnage is made in the dropdownlist, I want the method in my controller to be called which will fill in <div id=result></div> with the output from the method.
Perhaps I am approaching this problem wrong.
I suspect the problem is in my JavaScript.
Here is my approach:
View:
<div>#Html.DropDownList("MyDDL") </div>
<br>
<div id="result"></div>
JavaScript:
<script type ="text/javascript">
$(document).ready(function () {
$("#MyDDL").change(function () {
var strSelected = "";
$("#MyDDL option:selected").each(function () {
strSelected += $(this)[0].value;
});
var url = "HomeController/showInfo";
//I suspect this is not completely correct:
$.post(url, {str: strSelected},function (result) {
$("result").html(result);
});
});
});
</script>
Controller (Perhaps I shouldn't be using PartialViewResult):
public ActionResult Index()
{
List<string> myList = new List<string>();
List<SelectListItem> MyDDL = new List<SelectListItem>();
myList.Add("Tim");
myList.Add("Joe");
myList.Add("Jim");
//fill MyDDL with items from myList
MyDDL = myList
.Select(x => new SelectListItem { Text = x, Value = x })
.ToList();
ViewData["MyDDL"] = MyDDL;
return View();
}
[HttpPost]
public PartialViewResult showInfo(string str)
{
Person p = new Person(str); //name is passed to constructor
p.LoadInfo(); //database access in Person Model
ViewBag.Info = p.Info;
return PartialView("_result");
}
_result.cshtml:
<p>
#ViewBag.Info
</p>
Thanks You.
Change your script a little bit. Missing a # in the jQuery selecter for result div . Use the code given below
$.post(url, {str: strSelected},function (result) {
$("#result").html(result);
});
In my opinion if the javascript are in local don't need put $.post(url, {str: strSelected},function (result) {
You can use
//I suspect this is not completely correct:
$("#result").html(result);
try it
Did you try debugging p.LoadInfo() if it has any value? I also have some suggestions for your script:
Try adding keyup in your event so you can get the value in cases when the arrow keypad is used insted of clicking:
$("#MyDDL").on("change keyup", function () {
// you can get the dropdown value with this
var strSelected = $(this).val();
So I made the following changes and it worked:
View:
<div><%= Html.DropDownList("MyDDL") %> </div>
<br>
<span></span>
JavaScript:
<script type ="text/javascript">
$(document).ready(function () {
$("#MyDDL").change(function () {
var strSelected = $("#MyDDL option:selected").text();
var url = "/Home/showInfo";
$.post(url, {str: strSelected},function (result) {
$("span").html(result);
});
});
});
_result.cshtml:
#ViewBag.Info
The Controller was left unchanged.
I'm trying to use json for my web page's globalization options.. id like to change the labels of my form just by using a little dropdownbox and without refreshing the whole page and more interesting part is i got more than two form in my view.
so far i have done this:
My Json:
public JsonResult Globalx(String incoming)
{
System.Globalization.CultureInfo Cult = new System.Globalization.CultureInfo(incoming, true);
System.Threading.Thread.CurrentThread.CurrentCulture = Cult;
System.Threading.Thread.CurrentThread.CurrentUICulture = Cult;
Resources.Global.Culture = System.Threading.Thread.CurrentThread.CurrentCulture;
Global.ResourceManager.GetResourceSet(Cult, false, true);
ViewData["Name"] = Global.Name;
ViewData["Surname"] = Global.Surname;
ViewData["Birth"] = Global.Birth;
String lnginfo = Resources.Global.Culture.TwoLetterISOLanguageName.ToString();
ViewData["Languages"] = new SelectList(myList, "Value", "Text", lnginfo);
return Json(ViewData, JsonRequestBehavior.AllowGet);
}
My View:
#model MyCustomers.Models.Customers
#{
ViewBag.Title = ViewData["NewCustomer"];
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script type="text/javascript" language="javascript">
$(document).ready(function () {
function changeLang() {
var lang = $("#LanguageBox").val();
$.getJSON('#Url.Content("~/Home/People/")', { incoming: lang }, function (data) {
// what should i do here to get my label's language changed?
})
}
}
</script>
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "LanguageForm" }))
{
<fieldset>
<legend>#ViewData["LanguagesTitle"]</legend>
#Html.DropDownListFor(x => x.SelectedLanguage, (SelectList)ViewData["Languages"], new { onchange = "changeLang()", id = "LanguageBox" })
</fieldset>
}
#using (Html.BeginForm("PeopleForm", "Home", FormMethod.Post, new { enctype = "multipart/form-data", id = "PeopleForm" }))
{
<fieldset>
<legend>#ViewData["SalesContract"]</legend>
<div>
<div class="Name">
#Html.Label(ViewData["Name"].ToString()) <!--> HERE </!-->
#Html.EditorFor(x => x.People.Name)
</div>
<div class="Surname">
#Html.Label(ViewData["Surname"].ToString()) <!--> HERE </!-->
#Html.EditorFor(x => x.People.Surname)
</div>
<div class="Birth">
#Html.Label(ViewData["Birth"].ToString()) <!--> AND HERE </!-->
#Html.EditorFor(x => x.People.Birth)
</div>
</div>
</fieldset>
}
No im not actually using this method im refreshing the whole page each time to change the language of my labels but some friend of mine told me it could be done without refreshing and the first thing that came in my mind was Json.. I dont know if its possible or not im just trying. Any other ideas are wellcome.
I think the title is a little confusing and im asuming my problem here is understood so if anyone can find a better title please attempt to fix it.
In your Json result you would need to identify each of the labels that you have provided the text for, say each label has a Json object:
Id: 'label1',
Text: 'Enter your first name'
You provide one of these objects for each label on your page in an array,
{Id: 'label1', Text: 'Enter your first name'},
{Id: 'label2', Text: 'Enter your second name'},
{Id: 'label3', Text: 'Enter your telephone number'},
Then you deal with each of these on the requesting end,
$.getJSON('#Url.Content("~/Home/People/")', { incoming: lang }, function (data) {
for(i = 0; i < data.length; i++){
$('#'+data[i].Id).Html(data[i].Text);
}
})
I'm not 100% sure that Html will be the best thing to use - there may be sub DOM elements created by MVC that would need to be taken into account in your selector.
If you wanted to stick to the method you're using now you'll need to hard code each of the assigned values one at a time.
$.getJSON('#Url.Content("~/Home/People/")', { incoming: lang }, function (data) {
$('#Name').Html(data['Name']);
$('#Birth').Html(data['Birth']);
})