dropdowns in asp.net mvc 2 - asp.net-mvc-2

I have asp.net mvc application in c# language. I want to develop the scenario like, my page will have have the 4 dropdown controls. on the selection of first , second's item should be load, on selction of 2'nd, 3'rd dropdown should be load it item. where as 4'th is independent. but on 4'th dropdown I want to change the UI design. what strategy I have to use here? how can i implement this scenario here.?
Edited:
Controller->action
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetSubjects(int standardId)
{
List<Subject> subjectList = basicEntityManager.GetSubjects(standardId);
JsonResult result=Json(subjectList, JsonRequestBehavior.AllowGet);
return result;
}
i am able to debug this but not fetching data.
Script:
<script type="text/javascript">
$(function() {
$('#StandardId').change
(function() {
var url='/Test/GetSubjects';
fetchItems(url, { standardId: $(this).val() }, $('#SubjectId')
);
/* $('#SubjectId').change(function() {
fetchItems(
'/Test/GetChapters',
{
selectedItem1: $('#SubjectId').val(),
selectedItem2: $(this).val()
},
$('#SelectedItem3')
);
});*/
});
});
function fetchItems(url, data, ddl) {
$.getJSON(url, data, function(items) {
alert(items);
$.each(items, function() {
ddl.append
(
$('<option/>').val(this.Value).text(this.Text)
);
});
});
}
function OnStandardChange() {
var standard = document.getElementById("StandardId");
var subject = document.getElementById("SubjectId");
var ActionUrl = "/Test/GetSubjects/"
alert("Hi");
// $.getJSON('/Test/GetSubjects', { standardId: standard.val() }, function(data) { });
}
$('#StandardId').change(function() {
});
function OnSubjectChange() {
}
function OnChapterChange() {
}
function addOption(selectbox, text, value) {
var optn = document.createElement("OPTION");
optn.text = text;
optn.value = value;
selectbox.options.add(optn);
}
</script>

You could cascade with AJAX:
Model:
public class MyViewModel
{
public string SelectedItem1 { get; set; }
public IEnumerable<SelectListItem> Items1 { get; set; }
public string SelectedItem2 { get; set; }
public string SelectedItem3 { get; set; }
public string SelectedItem4 { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
// Load initial data
Items1 = Enumerable.Range(1, 5).Select(x => new SelectListItem
{
Value = x.ToString(),
Text = "item " + x
})
};
return View(model);
}
public ActionResult Items2(string selectedItem1)
{
// invoked to populate the second DDL
return Json(
Enumerable.Range(1, 3).Select(x => new { Value = x, Text = x }),
JsonRequestBehavior.AllowGet
);
}
public ActionResult Items3(string selectedItem1, string selectedItem2)
{
// invoked to populate the third DDL
return Json(
Enumerable.Range(1, 3).Select(x => new { Value = x, Text = x }),
JsonRequestBehavior.AllowGet
);
}
public ActionResult Items4(string selectedItem1, string selectedItem2, string selectedItem3)
{
// invoked to populate the fourth DDL
return Json(
Enumerable.Range(1, 3).Select(x => new { Value = x, Text = x }),
JsonRequestBehavior.AllowGet
);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
View:
<script type="text/javascript">
$(function () {
$('#SelectedItem1').change(function () {
fetchItems(
'<%= Url.Action("items2") %>',
{
selectedItem1: $(this).val()
},
$('#SelectedItem2')
);
});
$('#SelectedItem2').change(function () {
fetchItems(
'<%= Url.Action("items3") %>',
{
selectedItem1: $('#SelectedItem1').val(),
selectedItem2: $(this).val()
},
$('#SelectedItem3')
);
});
$('#SelectedItem3').change(function () {
fetchItems(
'<%= Url.Action("items4") %>',
{
selectedItem1: $('#SelectedItem1').val(),
selectedItem2: $('#SelectedItem2').val(),
selectedItem3: $(this).val()
},
$('#SelectedItem4')
);
});
$('#SelectedItem4').change(function () {
alert('changing UI');
});
});
function fetchItems(url, data, ddl) {
$.getJSON(url, data, function (items) {
$.each(items, function () {
ddl.append(
$('<option/>').val(this.Value).text(this.Text)
);
});
});
}
</script>
<% using (Html.BeginForm()) { %>
<%= Html.DropDownListFor(x => x.SelectedItem1, new SelectList(Model.Items1, "Value", "Text"))
<%= Html.DropDownListFor(x => x.SelectedItem2, Enumerable.Empty<SelectListItem>()) %>
<%= Html.DropDownListFor(x => x.SelectedItem3, Enumerable.Empty<SelectListItem>()) %>
<%= Html.DropDownListFor(x => x.SelectedItem4, Enumerable.Empty<SelectListItem>()) %>
<input type="submit" value="OK" />
<% } %>

Related

WebApi with Axios

Goal:
Use Axios with put and post method from react TS to Backend WebApi c#.
Problem:
The code doesn't work in relation to CORS.
What part from the backend source code am I missing in order to make backend to retrieve data that is PUT or POST?
Thank you!
React TS
import React from 'react';
import logo from './logo.svg';
import './App.css';
import axios from 'axios';
function App() {
const get = () => {
axios.get("https://localhost:7177/WeatherForecast/GetTestData")
.then(
response => console.log(response)
);
};
const update = () => {
const data =
{
CandyNumber: Number("1"),
Name: "asdf"
};
axios.put("https://localhost:7177/WeatherForecast/UpdateTestData", data)
.then(
response => console.log(response)
);
};
const add = () => {
const data =
{
CandyNumber: Number("1"),
content: "asdf"
};
axios.post("https://localhost:7177/WeatherForecast/AddTestData", data)
.then(
response => console.log(response)
);
};
return (
Get
Add
Uppdate
);
}
export default App;
backend
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
namespace WebTest2.Controllers
{
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet("GetTestData", Name = "GetTestData")]
[ProducesResponseType(typeof(List<Test>), StatusCodes.Status200OK)]
[ProducesResponseType(204)]
[Produces("application/json")]
public async Task<IActionResult> GetTestData()
{
List<Test> mytest = new List<Test>();
Test myTest = new Test()
{
CandyNumber = 1,
Name = "asdf"
};
Test myTest2 = new Test()
{
CandyNumber = 2,
Name = "asdf"
};
mytest.Add(myTest);
mytest.Add(myTest2);
return Ok(mytest);
}
[HttpPost("AddTestdata", Name = "AddTestdata")]
public async Task<IActionResult> AddTestdata(Test test)
{
List<Test> mytest = new List<Test>();
Test myTest = new Test()
{
CandyNumber = 1,
Name = "asdf"
};
Test myTest2 = new Test()
{
CandyNumber = 2,
Name = "asdf"
};
mytest.Add(myTest);
mytest.Add(myTest2);
return StatusCode(StatusCodes.Status204NoContent, null);
}
[HttpPut("UpdateTestdata", Name = "UpdateTestdata")]
public async Task<IActionResult> UpdateTestdata(Test test)
{
return StatusCode(StatusCodes.Status204NoContent, null);
}
}
public class Test
{
public int CandyNumber { get; set; }
public string Name { get; set; }
}
}
Program.cs
using Microsoft.OpenApi.Models;
using System.Reflection;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = ""
});
});
builder.Services.AddCors(options =>
{
options.AddPolicy("AllowAllHeaders",
corsbuilder =>
{
corsbuilder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.WithOrigins("http://localhost:3000/");
});
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
//--
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Add
app.UseCors(x => x
.AllowAnyMethod()
.AllowAnyHeader()
.SetIsOriginAllowed(origin => true) // allow any origin
.AllowCredentials()); // allow credentials
after " app.UseSwaggerUI();"

How to create a CDN server in dotnet core using MongoDB GridFS and AngularJs

We want to create a decoupled file server named CDN in .net core using MongoDB GridFS and angular js.
From various sources I tried my best to solve the issue.
And finally we done this.
I used Visual Studio 2017 and .NETCore 1.1
To do so I follow the followings:
1. Write Code in MongoDB GridFS
create an interface like
public interface IGridFsRepository : IDisposable
{
Task<string> UploadAsync(IFormFile file);
Task<bool> AnyAsync(ObjectId id);
Task<bool> AnyAsync(string fileName);
Task DeleteAsync(string fileName);
Task DeleteAsync(ObjectId id);
Task<GridFSDownloadStream<ObjectId>> DownloadAsync(string fileName);
Task<GridFSDownloadStream<ObjectId>> DownloadAsync(ObjectId id);
object GetAllFilesByContentType(string contentType, int skip, int
take);
object GetAllFiles(int skip, int take);
}
then create MongoDbCdnContext:
public abstract class MongoDbCdnContext
{
public IGridFSBucket GridFsBucket {get;}
protected MongoDbCdnContext(string connectionStringName)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.Build();
var connectionString =
config.GetConnectionString(connectionStringName);
var connection = new MongoUrl(connectionString);
var settings = MongoClientSettings.FromUrl(connection);
//#if DEBUG
// settings.ClusterConfigurator = builder =>
builder.Subscribe<CommandStartedEvent>(started =>
// {
// Debug.Write(started.Command);
// });
//#endif
var client = new MongoClient(settings);
var database = client.GetDatabase(connection.DatabaseName);
GridFsBucket = new GridFSBucket(database);
}
}
then implement it:
public class GridFsRepository : MongoDbCdnContext,
IGridFsRepository
{
public GridFsRepository() : base("MongoCdn")
{
}
public async Task<string> UploadAsync(IFormFile file)
{
var options = new GridFSUploadOptions
{
Metadata = new BsonDocument("contentType", file.ContentType)
};
using (var reader = new
StreamReader((Stream)file.OpenReadStream()))
{
var stream = reader.BaseStream;
var fileId = await
GridFsBucket.UploadFromStreamAsync(file.FileName, stream,
options);
return fileId.ToString();
}
}
public async Task<bool> AnyAsync(ObjectId id)
{
var filter = Builders<GridFSFileInfo>.Filter.Eq("_id", id);
return await GridFsBucket.Find(filter).AnyAsync();
}
public Task<bool> AnyAsync(string fileName)
{
var filter = Builders<GridFSFileInfo>.Filter.Where(x =>
x.Filename == fileName);
return GridFsBucket.Find(filter).AnyAsync();
}
public async Task DeleteAsync(string fileName)
{
var fileInfo = await GetFileInfoAsync(fileName);
if (fileInfo != null)
await DeleteAsync(fileInfo.Id);
}
public async Task DeleteAsync(ObjectId id)
{
await GridFsBucket.DeleteAsync(id);
}
private async Task<GridFSFileInfo> GetFileInfoAsync(string fileName)
{
var filter = Builders<GridFSFileInfo>.Filter.Eq(x => x.Filename,
fileName);
var fileInfo = await
GridFsBucket.Find(filter).FirstOrDefaultAsync();
return fileInfo;
}
public async Task<GridFSDownloadStream<ObjectId>>
DownloadAsync(ObjectId id)
{
return await GridFsBucket.OpenDownloadStreamAsync(id);
}
public async Task<GridFSDownloadStream<ObjectId>>
DownloadAsync(string fileName)
{
return await
GridFsBucket.OpenDownloadStreamByNameAsync(fileName);
}
public IEnumerable<GridFSFileInfoDto> GetAllFilesByContentType(string
contentType, int skip, int take)
{
var filter = Builders<GridFSFileInfo>.Filter
.Eq(info => info.Metadata, new BsonDocument(new
BsonElement("contentType", contentType)));
var options = new GridFSFindOptions
{
Limit = take,
Skip = skip,
};
var stream = GridFsBucket.Find(filter, options)
.ToList()
.Select(s => new GridFSFileInfoDto
{
Id = s.Id,
Filename = s.Filename,
MetaData = s.Metadata,
Length = s.Length + "",
UploadDateTime = s.UploadDateTime,
})
.ToList();
return stream;
}
public IEnumerable<GridFSFileInfoDto> GetAllFiles(int skip, int take)
{
var options = new GridFSFindOptions
{
Limit = take,
Skip = skip,
};
var stream = GridFsBucket.Find(new
BsonDocumentFilterDefinition<GridFSFileInfo<ObjectId>>(new
BsonDocument()), options)
.ToList()
.Select(s => new GridFSFileInfoDto
{
Id = s.Id,
Filename = s.Filename,
MetaData = s.Metadata,
Length = s.Length + "",
UploadDateTime = s.UploadDateTime,
})
.ToList();
return stream;
}
public void Dispose()
{
GC.SuppressFinalize(this);
}
}
then create a controller in .netcore web api
[EnableCors("AllowAll")]
[ValidateModel]
[Route("api/files")]
public class FileController : Controller
{
private readonly IGridFsRepository _gridFsManager;
public FileController(IGridFsRepository gridFsRepository)
{
_gridFsManager = gridFsRepository;
}
[AllowAnonymous]
[HttpGet("{fileName}",Name = "GetByFileName")]
public async Task<IActionResult> GetByFileName(string fileName)
{
return Ok(await _gridFsManager.DownloadAsync(fileName));
}
[AllowAnonymous]
[HttpGet("{id}",Name = "GetById")]
public async Task<IActionResult> GetByFileName(ObjectId id)
{
return Ok(await _gridFsManager.DownloadAsync(id));
}
[HttpPost]
public async Task<IActionResult> Upload([FromForm] IFormFile file)
{
if (file != null)
{
if (file.ContentType.Contains("image"))
return BadRequest("Sorry only image jpg/jpeg/png
accepted");
if (file.Length >= (300 * 1024))
return BadRequest($"Sorry {file.FileName} is exceeds
300kb");
await _gridFsManager.DeleteAsync(file.FileName);
await _gridFsManager.UploadAsync(file);
}
return NoContent();
}
[HttpDelete]
public async Task<IActionResult> Delete(string id)
{
await _gridFsManager.DeleteAsync(id);
return NoContent();
}
}
please do not forget to resolve dependency:
services.AddScoped<IGridFsRepository, GridFsRepository>();
to file from html:
<div class="btn">
<span>Logo</span>
<input type="file" data-ng-model="cp.data.file"
id="selectedFile" name="selectedFile">
</div>
lets go to UI layer:
first create an angular factory:
(function () {
"use strict";
angular.module("appCdn", [])
.factory('fileUploader', ["$http", function ($http) {
return {
upload: function (url, file, fileMaxSize, fileName, callback) {
if (this.isValidFileSize(fileMaxSize, file)) {
var fd = new FormData(); //Create FormData object
if (fileName)
fd.append("file", file, fileName);
else
fd.append("file", file);
$http.post(url, fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}).success(function (data) {
callback();
}).error(function (data) {
Materialize.toast("Sorry! error in file upload", 4000, 'red');
});
} else {
Materialize.toast("Sorry! " + file.name + " exceeds 300kb", 4000, 'red');
}
},
isValidFileSize: function (maximumAllowedSize, file) {
if (file.size >= maximumAllowedSize) {
return false;
} else {
return true;
}
}
};
}
]);
})();
after that create an angular controller:
angular.module('ecom').controller('companyProfileCtrl',
['$http', 'config', "confirmation", "fileUploader",companyProfile]);
function companyProfile($http, config, confirmation, fileUploader) {
var vm = this; vm.getProfile = function () {
$http.get(config.apiUrl + "companyProfile")
.success(function (response) {
vm.data = response;
});
};
vm.save = function (profile) {
confirmation.confirm(function () {
$http.post(config.apiUrl + "companyProfile", profile)
.success(function (data) {
var fileName = "";
if (profile.id) {
fileName = profile.id;
} else {
fileName = data;
}
vm.upload(fileName,
function () {
Materialize.toast("succeeded", 4000, 'green');
window.location.href = window.history.back();
});
})
.error(function (data) {
Materialize.toast(data, 4000, 'red');
});
});
};
vm.upload = function (fileName, callback) {
var photo = document.getElementById("selectedFile");
var file = photo.files[0];
if (file) {fileUploader.upload(config.cdnUrl + "files",
//300kb
file, 1024 * 300, fileName, callback);
}
};
};
finally to show the image in html:
<div><img src="http://localhost:41792/api/files/{{cp.data.id}}"
class="img-responsive visible-md visible-lg img-margin-desktop"
width="350" height="167" />
</div>
finally we done this. this is all.
I always looking forward to receiving criticism.

How return Partial from Action getJSON

I'm having a problem with method using $.getJSON. It's very simple and it looks like that:
Take ID из DropDownlList CategoryId
<div id="partial" class="editor-label">
#* #Html.Partial("");*#
</div>
$(document).ready(function () {
$('#CategoryId').change(function () {
$.getJSON('/Publication/AjaxAction/' + this.value, {},
function (html) {
$("#partial").html(html);
alert("go");
});
});
});
send in
public ActionResult AjaxAction(int Id)
{
if (Request.IsAjaxRequest())
{
if (Id== 1)
{
ViewBag.SourceTypeId = new SelectList(db.SourceTypes, "Id", "Title");
ViewBag.CityId = new SelectList(db.Cities, "Id", "Title");
return Partial("_CreateStatya");
}
}
return PartialView();
}
Could you please tell me how to return Partial in ??
<div id="partial" class="editor-label">
#* #Html.Partial("");*#
</div>
$(document).ready(function ()
{ $('#CategoryId').change(function ()
{ $.get('#Url.Action("AjaxAction","Publication")',
{id:$('#CategoryId').val()}, function (html)
{ $("#partial").html(html);
alert("go"); },'html');
}); });

Fine Uploader in Form Doesn't Submit Model Data into Controller

I have 2 questions:
1.) I have placed the Fine Uploader in a form and now I'm wondering why I don't see the filled content of the entry fields in my controller. How I can solve that?
2.) How can I do field validations before the upload process fires?
I hope someone can help!
Here is my code:
Model:
public class UploadFileModel
{
[StringLength(100)]
[Display(Name = "* Title:")]
public string Title { get; set; }
[StringLength(300)]
[Display(Name = "Description:")]
public string Description { get; set; }
}
View:
#model mowee.Models.UploadFileModel
<link href="~/Scripts/fineuploader/fineuploader-3.5.0.css" rel="stylesheet" />
#using (Html.BeginForm("UploadFile", "Home", FormMethod.Post, new { id = "uploadForm", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<fieldset>
<legend>Video Upload</legend>
<ol>
<li>
#Html.LabelFor(m => m.Title)
#Html.TextBoxFor(m => m.Title, new { #Class = "action add", title = "Enter your video/movie title here." })
</li>
<li>
#Html.LabelFor(m => m.Description)
#Html.TextAreaFor(m => m.Description, new Dictionary<string, object> { { "rows", "3" } })
</li>
</ol>
<div id="bootstrapped-fine-uploader"></div>
<script src="~/Scripts/fineuploader/fineuploader-3.5.0.js"></script>
<script>
function createUploader() {
var uploader = new qq.FineUploader({
element: document.getElementById('bootstrapped-fine-uploader'),
multiple: false,
validation: {
sizeLimit: 2147483648 //2GB
},
request: {
endpoint: '/Home/UploadFile'
},
text: {
uploadButton: '<div><i class="icon-upload icon-white"></i>* Upload Video</div>'
},
template: '<div class="qq-uploader span12">' +
'<pre class="qq-upload-drop-area span12"><span>{dragZoneText}</span></pre>' +
'<div id="btnUpload" class="qq-upload-button btn btn-success" style="width: 33%;">{uploadButtonText}</div>' +
'<span class="qq-drop-processing"><span>{dropProcessingText}</span><span class="qq-drop-processing-spinner"></span></span>' +
'<ul class="qq-upload-list" style="margin-top: 10px; text-align: center;"></ul>' +
'</div>',
classes: {
success: 'alert alert-success',
fail: 'alert alert-error',
dropActive: "cssClassToAddToDropZoneOnEnter"
}
});
}
window.onload = createUploader;
</script>
</fieldset>
}
Controller:
[HttpPost]
[AllowAnonymous]
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult UploadFile(string qqfile, UploadFileModel myModel)
{
if (ModelState.IsValid)
{
try
{
HttpPostedFileBase uploadFile = null;
uploadFile = Request.Files[0];
if (uploadFile != null && uploadFile.ContentLength > 0)
{
if (myModel.Title != null || myModel.Description != null)
{
**//but UploadFileModel is null. WHY??????? Anyone an idea what i did wrong???
//write data to DB**
}
}
else
{
ModelState.AddModelError("", "Please choose a video/movie.");
return Json(new { success = false, message = "Please choose a video/movie." }, "application/json");
}
}
catch (Exception ex)
{
ModelState.AddModelError("", "An error occured. Try again.");
mailUtils.SendBugMail(ex, this.HttpContext);
return Json(new { success = false, message = "An error occured during upload. Try again." }, "application/json");
}
return Json(new { success = true, VideoLink = #ViewBag.VideoLink, VideoTranscoded = #ViewBag.Transcoded }, "application/json");//"text/html");
}
return Json(new { success = false, message = "An error occured during upload. Try again." }, "application/json");
}
OK. I figured it out. The params can be set on callback 'onSubmit' with setParams like that:
callbacks: {
onSubmit: function (id, fileName, responseJSON) {
uploader.setParams({
idxTitle: $('#titleId').val(),
idxAuthor: $('#authorId').val(),
idxEmail: $('#emailId').val()
});
},
And it works fine!
Addressing your questions:
You should really have a look at the MVC4 example in the Fine Uploader server-side examples repository. Model your server-side code after this example, and you should be fine. I personally am not an MVC4 developer, but I know the example I have linked to works.
You can make use of onValidate and onValidateBatch callbacks to perform your own validation tasks. Please have a look at the callbacks documentation for more info.

Cascading dropdown

Is there any alternative to json data to cascade dropdowns?
I am using country and state dropdown but cascading the data with json take too much time
[HttpGet]
public ActionResult States(int countryId)
{
DateTangoEntities _db = new DateTangoEntities();
var tset = _db.States.Where(r => r.CountryID == countryId).Select(r =>
new { r.StateName, r.StateID });
return Json(tset, JsonRequestBehavior.AllowGet);
}
and here is the jquery part
$(document).ready(function () {
var countries = $("#Country");
var regions = $("#States");
countries.change(function () {
regions.find('option').remove();
$.getJSON('/Profile/States', { countryId: countries.val() }, function (data) {
$(data).each(function () {
$('#States').append('<option value="' + this.StateID + '">' + this.StateName + '</option>').resetSS();
});
});
});
});