I require to pass a variable from one controller action to javascript in another view..
In controller Action A:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection args)
{
var obj = new ProjectManagernew();
var res = new ProjectViewModelNew();
try
{
UpdateModel(res);
if (obj.AddUpdateOrderField(res))
{
ViewBag.RecordAdded = true;
ViewBag.Message = "Project Added Successfully";
TempData["Name"] = "Monjurul Habib";
}
return View(res);
}
catch (Exception)
{
//ModelState.AddRuleViolations(res.GetRuleViolations());
return View(res);
}
}
In another javascript:
function gridA() {
var message = '#TempData["Name"]';
$('#mylabel').text(message);
}
Only Tempdata works But not the first time its working from the second time after iam calling the action controller
I want to temp data to work rom the first time
I want t clear the data after using
If your javascript is inside the same view that takes the ProjectViewModelNew, you can use a different type for your view, for example you can use composition:
public class MyCompositeClass
{
ProjectViewModelNew ProjectViewModel{get;set;};
string Name{get;set;}
}
and then your action method would be:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection args)
{
var obj = new ProjectManagernew();
var res = new ProjectViewModelNew();
var myView = new MyCompositeClass();
try
{
UpdateModel(res);
myView.ProjecViewModel = res;
if (obj.AddUpdateOrderField(res))
{
ViewBag.RecordAdded = true;
ViewBag.Message = "Project Added Successfully";
myView.Name= "Monjurul Habib";
}
return View(myView);
}
catch (Exception)
{
//ModelState.AddRuleViolations(res.GetRuleViolations());
return View(myView);
}
}
and your js would be:
function gridA() {
var message = '#Model.Name';
$('#mylabel').text(message);
}
Related
Good day
i'm trying to hard delete a soft deleted records, i have a Method Task PermanantlyDeleteDeal(GetDealInput input) When i call the method it does not go in.
Since boilerplate 0.9.6 is not hard deleting, i'm now using Database>DataContext.cs class to execute hard delete
Here is my DataContext class
public class DataContext : DbContext
{
public virtual DbSet<Deal> Deal{ get; set; }
public DataContext()
: base("Default")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}}
Here is the function on javaScript that u call the method
function DeleteLead(btnCaller) {
abp.message.confirm('Lead will be deleted.', 'Are you sure?', function (isConfirmed) {
if (isConfirmed) {
var button = $(btnCaller);
var proposalId = button.data('content');
var proposalObject = Object({
Id: proposalId
});
abp.ui.setBusy();
_leadService.permanantlyDeleteLead(proposalObject).done(function (result) {
abp.notify.success('Successfully deleted a proposal', 'Quotation deleted');
Refresh();
}).always(function () {
abp.ui.clearBusy();
});
}
});
}
Here is the PermanantlyDeleteComment
public async Task PermanantlyDeleteDeal(GetDealInput input)
{
UserFriendlyException ufex = null;
try
{
DataContext db = new DataContext();
using (Repository.Repository<Deal> repo = new Repository.Repository<Deal>(db))
{
using (Repository.Repository<DealComment> dealCommentRepo = new Repository.Repository<DealComment>(db))
{
using (Repository.Repository<Proposal> proposalRepo = new Repository.Repository<Proposal>(db))
{
using (Repository.Repository<Quotation> quotationRepo = new Repository.Repository<Quotation>(db))
{
Deal deal = repo.GetById(input.Id);
List<DealComment> listOfDealComments = dealCommentRepo.GetAll().Where(dc => dc.DealId == deal.Id).ToList();
List<Proposal> listOfProposals = proposalRepo.GetAll().Where(x => x.DealId == deal.Id).ToList();
List<Quotation> listOfQuotations = quotationRepo.GetAll().Where(x => x.DealId == deal.Id).ToList();
if (listOfProposals.Count > 0 || listOfQuotations.Count > 0)
{
string message = string.Empty;
message += listOfProposals.Count > 0 ? "Cannot delete deal, this deal is linked to:\nProposals\n" : "Cannot delete deal, this deal is linked to:\n";
foreach (var item in listOfProposals)
{
message += $"- {item.Application}\n";
}
message += listOfQuotations.Count > 0 ? "Quotations:\n" : "";
foreach (var item in listOfQuotations)
{
message += $"- {item.Description}\n";
}
ufex = new UserFriendlyException("Ooops! There is a problem.", $"{message}");
throw ufex;
}
else
{
foreach (var item in listOfDealComments)
{
dealCommentRepo.Delete(item);
dealCommentRepo.SaveChanges();
}
if (deal != null)
{
repo.Delete(deal);
repo.SaveChanges();
}
}
}
}
}
}
}
catch
{
if(ufex != null)
throw ufex;
else
throw new UserFriendlyException("Ooops! There is a problem.",$"Deal with Id[{input.Id}] could not be deleted.");
}
}
Abp.Boilerplate 0.9.6
Abp.EntityFramework 0.9.6
I have had the same problem in the past, to fix the issue i had to make sure that The version(s) of entity framework being referenced by the project(s) is the same version of entity framework for all projects in the solution.
And if required in The DataContext class make sure to enable
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
the key is to have the same names as what the ABP context is generating.
I have a register form with asp.net web api 2 identity.
This is my register function:
// POST api/Account/Register
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
try
{
...send email
}
catch (Exception ex)
{
throw new Exception(ex.ToString());
}
return Ok();
}
If ModelState is not valide it returns something like this:
How can I get this detailed error?
I'm looking for a way to dynamically get all detailed errors from ModelState.
I'm not sure if I should do it on the Web api or in javascript when I get the response.
I ended up writing the following function on my AccountController.
It loops through the errors on the ModelState, adds them to a list and then it loops through the list and adds them to the ModelState.
public void SetCustomError()
{
var errors = new List<string>();
foreach (var state in ModelState)
{
foreach (var error in state.Value.Errors)
{
errors.Add(error.ErrorMessage);
}
}
foreach (var error in errors)
{
ModelState.AddModelError("CustomError", error);
}
}
And then on my javascript I handled it like this:
function showError(jqXHR) {
if (jqXHR) {
jsonValue = jQuery.parseJSON(jqXHR.responseText);
if (!jsonValue.modelState["customError"] == undefined) {
$("#error").text(jsonValue.modelState["customError"][0]);
}
else {
$("#error").text(jsonValue.modelState[""][0]);
}
$("#modalError").dialog();
}
}
I just got handed a new project where most of the job was already done but I needed to change some things for my project. I have a self hosted server setup like this in a consoleapp:
using (var server = new HttpSelfHostServer(config))
{
server.OpenAsync().Wait();
Console.WriteLine("Press enter to exit");
Console.ReadLine();
}
and a route configured like this:
private static HttpSelfHostConfiguration CreateWebServerConfiguration()
{
var config = new HttpSelfHostConfiguration(string.Format("http://{0}:{1}", Environment.MachineName, 80));
config.Routes.MapHttpRoute("Api", "api/{controller}/{id}/{value}", new {id = RouteParameter.Optional, value = RouteParameter.Optional });
config.Routes.MapHttpRoute("Defect", "defect/{action}/{id}", new { controller = "Defect", action = RouteParameter.Optional, id = RouteParameter.Optional });
config.Routes.MapHttpRoute("Content", "content/{action}/{file}", new { controller = "Content"});
config.Routes.MapHttpRoute("Default", "{controller}/{action}/{id}/{date}", new { controller = "Home", action = "Index", id = RouteParameter.Optional, date = RouteParameter.Optional });
var templateConfig = new TemplateServiceConfiguration { Resolver = new DelegateTemplateResolver(name => ReadFileContent("Views", name))};
Razor.SetTemplateService(new TemplateService(templateConfig));
return config;
}
This works perfectly, but I ran into a situation, where I didn't want the front end to pull with a timer on the server(currently auto refresh every 5 min). I want the server to update the frontend, when there is something new to update. I found the solution to this which would be websockets, but I have a lot of problems using those.
my .js file:
(function() {
if ("WebSocket" in window) {
alert("WebSocket is supported by your Browser!");
} ws://' + window.location.hostname + window.location.pathname.replace('index.htm', 'ws.ashx') + '?name='
var socket = new WebSocket("ws://localhost:80/WebsocketServer.cs");
socket.onmessage = function(event) {
alert("message recv.");
alert(event.data);
};
socket.onopen = function() {
alert("open");
}
socket.onerror = function(errorEvent) {
alert("Error");
alert(errorEvent);
};
socket.onclose = function(closeEvent) {
alert(closeEvent.code);
}
})();
I found multiple examples like this one: https://blog.simpleisbest.co.uk/2012/05/01/websockets-with-asp-net-4-5-and-visual-studio-11/ but it doesn't seem to work for me, this is my files:
WebsocketServer.cs
public class WebsocketServer : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
if (context.IsWebSocketRequest)
{
context.AcceptWebSocketRequest(new WebSocketManager());
}
}
public bool IsReusable
{
get { return false; }
}
}
WebSocketManager.cs
public class WebSocketManager : WebSocketHandler
{
public static WebSocketCollection clients = new WebSocketCollection();
public override void OnClose()
{
clients.Remove(this);
}
public override void OnError()
{
}
public override void OnMessage(string message)
{
}
public override void OnOpen()
{
clients.Add(this);
clients.Broadcast("Connected");
}
}
The frontend returns closing code 1006 or CLOSE_ABNORMAL. My guess is the link to the backend isn't created?
In the Asp.Net Project MVC with SignalR, I am trying to iterate over a object returned by Service in the Javascript Client. I get the below compile error for the foreach statement present in the below code
foreach statement cannot operate on variables of type 'System.Threading.Tasks.Task>' because 'System.Threading.Tasks.Task>' does not contain a public definition for 'GetEnumerator'
Can someone advise what changes should be done either in View/Service call ?
View Code
#model System.Threading.Tasks.Task<List<JobCurrentStatusDetails>>
<script type="text/javascript">
var connection = $.hubConnection();
var hub = connection.createHubProxy("JobDetailsHub");
hub.on('updateData',function(jSonRefreshData){
console.log(jSonRefreshData);
});
hub.invoke('NotifyUpdates').done(function(jSonRefreshData){
#Model = jSonRefreshData
#{int countTiles = 0;}
#foreach(item in Model)
{
if(item.color == "red")
{}
if(item.color == "green")
{}
}
});
</script>
Adding Server Side code
public async Task<List<JobCurrentStatusDetails>> NotifyUpdates()
{
var hubContext = lobalHost.ConnectionManager.GetHubContext<JobDetailsHub> ();
if (hubContext != null)
{
db = DataAccess.DataAccessModels.GetDashboardCounts();
return await hubContext.Clients.All.updateData(db);
}
else return null;
}
The Controller code is below :
public ActionResult Index()
{
DataAccess da = new DataAccess();
var jobDetailService = new JobDetailsService(da);
return View(jobDetailService.NotifyUpdates());
}
You are returning a Task as the Model. You could do this instead:
public List<JobCurrentStatusDetails> NotifyUpdates()
{
var hubContext = lobalHost.ConnectionManager.GetHubContext<JobDetailsHub>();
if (hubContext != null)
{
db = DataAccess.DataAccessModels.GetDashboardCounts();
return hubContext.Clients.All.updateData(db).Result;
}
else return null;
}
I have this code.
The objective of this js is through the dropwdown load the textbox UserMR
But it never finds the UserMR.
I call UserMr model inside Star instantiating a new object.
relationships:
Star contains idModel
Model does not contain IDStar
What is going on?
Model
[CustomValidation(typeof(StarValidation), "DateValidate")]
public partial class Star
{
public virtual string UserMR { get { return this.User.UserMR; } set { this.UserMR = value;} }
public Model User = new Model();
View inside "STAR"
#Html.EditorFor(i => i.IdModel, "StarModel", new { onchange = "updateUserMR($(this))" })
#Html.DisplayFor(i => i.UserMR)
<script type="text/javascript">
function updateUserMR(model) {
var user = model.brother("#Html.NameFor(x => x.UserMR)");
var idModel = model.val();
user.empty();
if (idModel != null && idModel != "")
user.loadOptions("#Url.Action("ListJsonUserMR", "Model")?idModel=" + idModel, true, true);
}
</script>
Controller
public JsonResult ListJsonUserMR(int idModel)
{
var model = this.service.GetUserMr(idModel).Select(x => new
{
Value = x.Id,
Description = x.UserMR
});
return this.Json(model, JsonRequestBehavior.AllowGet);
}
Service
public IEnumerable<Model> GetUser(int idModel)
{
return base.context.Models
.Where(x => x.Id == idModel);
}
Error