FAQ Database Discussion Community


Use Bearer Token Authentication for API and OpenId authentication for MVC on the same application project

c#,asp.net-mvc-4,oauth-2.0,openid,identityserver3
I am trying to use both OpenId and Bearer token authentication on my application through Identity Server. The problem currently is that once I have authenticated the user, I still need to get a bearer token to be able to call any action methods for my Asp.Net MVC application. Here...

Return to the same view when no image is selected

asp.net-mvc-4,razor,json.net,entity-framework-5,c#-5.0
I have an upload control. But if the user didnt select an image and the press on the upload button, the user will get an message that he/she has to go back and try again, like this: if (isSavedSuccessfully) { return Redirect(Url.Action("Edit", "Account") + "#tabs-2"); } else { return Json(new...

Partial View's checkbox state not returned to controller

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor
I have a main view whose Model is of type FacilityViewModel. The main view loads a partial view that also contains a partial view. Both partial views have a model of type FiltersViewModel. The most nested partial view loops through a dictionary and creates a checkbox for each item to...

Pass a javascript variable as parameter to @url.Action()

javascript,asp.net-mvc-4,url.action
is it possible to pass a javascript variable as a parameter to @url.Action(), because as far as i know there may be server and client side issue, my requirement is i have to download the file according to filter, and ajax call doesnot work with downloading the file. so i...

RedirectToAction to another Controller and passing parameters

c#,asp.net,asp.net-mvc,asp.net-mvc-4
I'm new in C# and espacially in ASP.NET MVC. I have my HomeController, which contains this method: public ActionResult Error(Error error) { return View(error); } Now I have another Controller, which have the following line inside: return RedirectToAction("Error","Home", new { Error = (new Error("ErrorName","ErrorDescription"))} ); As you might notice, I...

C# mvc4 - direct URL to controller

c#,asp.net-mvc-4,url,redirect
I have an external URL that points directly to a function in my controller but when I click on it for the first time, instead of reaching the page, I get to the home page. However, on the second click (and the following ones), I can reach the desired page....

Angularjs ng-show doesn't work with Viewbag

angularjs,asp.net-mvc-4
In Angularjs template is it possible to use ViewBag.Property in ng-show? I set some viewbag in my controller/action like this ViewBag.AllowExport = false; when i tried following nothing happen <div ng-show="@ViewBag.AllowExport"> <a href="JavaScript:void(0);">Export</a> </div> Above Div is still showing even if AllowExport = false; Is my syntax is wrong here...

MVC - How to render a 'a href' link in a View that's been stored in a database?

asp.net-mvc,asp.net-mvc-4,model-view-controller
Question background: I have an MVC4 app whos homepage data is supplied from a View Model. The Issue: Within the View Model I have a property called AboutUsDescOne This is set from the Controller and Action Method from data that has been retrieved from a database. Within the data set...

Why mozilla changes the characters when i use the .net mvc statement redirect?

c#,asp.net-mvc-4,redirect,mozilla
I'm trying to redirect to an external website when everything is done, but firefox changes the http word on the url for a weird set of characters. This is my server side code: [HttpPost] public ActionResult Postular(INFO_BASE_POSTULACION_model pInfoPostulacion) { string rutMD5 = Request["rutMD5"]; int idRegion = Convert.ToInt32(Request["idRegion"]); int idInstrumento =...

How do I set the URL for a new page/view when using ASP.NET MVC

c#,asp.net,asp.net-mvc,asp.net-mvc-4
I'm just starting to use/wrap my head around MVC, but I'm still a little confused about where the actual URL for each view is defined. So far, I have 2 controllers and 2 views. The first controller works, and creates the correct view under the URL http://localhost:60480/Example, but I'm not...

check for value null on razor syntax

c#,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,razor
The following code is failing because propiedadesFormularioDetalle is null. I placed an IF before the block code but still not working, if I remove one of the bracked, then it wont compile @if (propiedadesFormularioDetalle != null) { } <div class="panel panel-default"> <div class="panel-heading">Propiedades adicionales</div> <div class="panel-body"> <dl class="dl-horizontal"> @foreach (KeyValuePair<string,...

redirect to actionResult method from an api

c#,asp.net-mvc-4,asp.net-web-api
[HttpPost] public void insertData(string productid) { //insert to db string uri = this.Url.Link("Default", new { controller = "AddProducts", action = "Index" }); //Response.Redirect(Url.Action("", "")); } after inserting to the database i want to redirect to an actionResult method.i have a void method, what do i return it as?...

Prevent page refresh on submit button click

asp.net-mvc-4
I am working in Mvc4. Creating a validation. When I am clicking the submit button and the validation is getting failed and the full page is getting refreshed to display the validation messages. I do not want my page to get refreshed. And another question is is there any way...

File upload control in asp.net mvc

c#,asp.net,asp.net-mvc,asp.net-mvc-4
I have written a fileupload control in asp.net mvc.But as of now the logic what i am doing is, i am downloading excel file in to server locally and then processing data and pushing in to oracle database.But some servers due to permission issues , i am not able to...

How can I bind a list model which contains a complex type in MVC4?

c#,asp.net-mvc,asp.net-mvc-4
I have a form with input elements like this: ... <input type="hidden" name="orders[0].ID" value="1"> <input type="text" name="orders[0].Name" value="Some name"> <input type="date" name="orders[0].Date" value="09/08/2014"> <input type="time" name="orders[0].Time" value="5:16 AM"> ... <input type="hidden" name="orders[1].ID" value="2"> <input type="text" name="orders[1].Name" value="Some name2"> <input type="date" name="orders[1].Date" value="09/08/2014"> <input type="time" name="orders[1].Time"...

How to bind anonymous type to viewModel in ASP.NET-MVC

c#,asp.net-mvc,asp.net-mvc-4
I need to bind the anonymous type output to viewmodel to pass it on view. the need is to i have to bind the checkbox with the model value i am using join to fetch the value but dont know how to pass it to view. my join query is...

MVC Push notification from server to client side

asp.net-mvc-4,push-notification
This question may sound lame but. Is there any technique to send push notificaiton from server to client side, regarding the server status. For Example: While Login Notification in Client Side in sequence: Validating User ... Validating Digital Certificate ... Sorting downloadable file ... Preparing to download ... If its...

Using dropdownlistfor for model with list property

c#,asp.net-mvc,asp.net-mvc-4,model
How do I use dropdownlistfor for this viewmodel? public class ViewModel { public IEnumerable<Model1> model1{ get; set; } } public class Model1 { public string Name { get; set; } public int Id{ get; set; } } How should I do this? @model Models.ViewModels.ViewModel @Html.DropDownListFor(model => model.model1) ...

MVC Routing News Pages

asp.net-mvc-4,asp.net-mvc-routing
I have managed to get my MVC project to present a list of news items in an SEO friendly manner: /News/ - to present the list /News/NewsItem/id/news-item-title - the individual news item What I would really like is: News/id/news-item-title Exactly how Stackoverflow presents its questions. However, I cant seem to...

Why is my View not displaying value of ViewBag?

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor
I have a little blog application with posts and tags. This is my model for Post: namespace HelloWorld.Models { public class Post { [Required] [DataType(DataType.Text)] public string Title { get; set; } [Required] [DataType(DataType.MultilineText)] public string Description { get; set; } [Required] [DataType(DataType.DateTime)] public DateTime PostDate { get; set; }...

A property of model becomes null while posting

asp.net-mvc-4
I'm new to MVC. Now I'm trying with a simple demo of MVC that to print Customer's information to screen and update it, send back to database. I have no idea why the Customer's ID becomes null while the others are fine. I want to display Customer's ID to the...

startIndex cannot be larger than length of string

c#,entity-framework,asp.net-mvc-4
I try to check if a foldername doesnt has a extensie. Because I want to change the name of the folder. But you can also change the name of a file. But I get this error: "startIndex cannot be larger than length of string.\r\nParameter name: startIndex"} By this line: string...

Mvc Remote Attribute is sending “undefined” in query string

c#,asp.net,asp.net-mvc,asp.net-mvc-4
I'm trying to remote validate some code and for the parameter, its passing undefined in as a parameters. Here is my validation code: [OutputCache(Location = OutputCacheLocation.None, NoStore = true)] public class ValidationController : Controller { public JsonResult IsUserNameAvailable(string userName, int? UserId) { var users = new BusinessLayer.BdsAdmin.Users(); if (UserId ==...

access a page in the MVC Global.asax

c#,asp.net,asp.net-mvc,asp.net-mvc-4
I want to redirect to a page in the case that does not accomplish a condition in the global.asax in method application start... redirects to a warning page like this:... protected void Application_Start() { if (MyClass.Warnning == "2") { Response.Redirect("~/warningPage.aspx"); } } but it shows me the following error: response...

how to use Html.RenderPartial with ViewModel

asp.net-mvc,asp.net-mvc-4,asp.net-mvc-partialview,renderpartial
i am trying to create user reviews under each product, i used Html.RenderAction Html.RenderAction("ProductReviewTest", new { id = productids }); it works fine but it takes 9.4s to load the product page with the reviews, so tried Html.RenderPartial but gives error my product view: @model MVCProduct.Models.Product <!--here displaying products--> <!--displaying...

Using Bootstrap 3 DateTimePicker in ASP.NET MVC Project

jquery,asp.net-mvc,twitter-bootstrap,asp.net-mvc-4,bootstrap-datetimepicker
I want to use the Bootstrap 3 DateTimePicker. I added it to my ASP.NET project using NuGet. Here's my BundleConfig.cs: bundles.Add(new StyleBundle("~/Content/Bootstrap").Include("~/Content/bootstrap.css", "~/Content/bootstrap-theme.css", "~/Content/bootstrap-theme.min.css", "~/Content/bootstrap.min.css", "~/Content/less/_bootstrap-datetimepicker.less", "~/Content/less/bootstrap-datetimepicker-build.less")); bundles.Add(new ScriptBundle("~/Scripts/Bootstrap").Include( "~/Scripts/moment.min.js", "~/Scripts/bootstrap.js",...

Return MVC view while submitting serialized data(MVC, Ajax)

jquery,ajax,asp.net-mvc,asp.net-mvc-4
I am new to mvc I have this AJax and Controller, i need to return a view that say "Email Sent" for now the controller redirected me to the http://localhost:1365/?Name=as&Adress=adsads&city=a&state=as&zip=as&phone=asas&Message=a Ajax Call <script> $(function () { $("#JqAjaxForm").submit(function () { debugger; var sdata = $("#JqAjaxForm").serialize(); alert(sdata); senddata = { "daye": sdata...

MVC View trying to parse 2 strings in Details view

asp.net-mvc,asp.net-mvc-4,razor
its an MVC razor project with entity framework, simple record view/edit/create in View, the details cshtml I want to read out just 2 of the record values and based on their contents, create a label. <h1 @if(Model.unittype == "PRP" && Model.name =="TTO"){string x = "CISCO";}else x = "---";>x</h1> not a...

Use “Contains” to match part of string in lambda expression

c#,jquery,asp.net-mvc-4,lambda
I have this MVC page where I have three different "input" elements, all the same class, using the jQuery autocomplete. On any one of them I am doing this in the controller: [HttpGet] public ActionResult GetAllItemsEdit(string data, string source) { List<TextValuePair> items = InventoryControlRepository.GetAllItemsTVP(); var result1 = items.Where(item => item.Text.Contains(data.ToUpper())).ToList();...

MVC 4 - pass parameter to controller on button click

asp.net-mvc-4
I have an MVC 4 project that has a save button that when clicked asks the user to confirm and then submits the whole form back to the controller with the model as input, not formCollection. Now I need to add another button to the form called Submit. How can...

Conflicted with the REFERENCE constraint. How to solve this?

asp.net-mvc-4,nhibernate
I catch this GenericADOException exception but some unexpected exception comes again when I do genRep.Update(userW). How can I fix this problem? This is my code: public ActionResult DeleteUser(long? UserID) { GenericRepositoryV2 genRep ; if (!SecurityService.IsLoggedIn(Session)) { return SecurityService.LoginAndRedirect(Request); } try { genRep = new GenericRepositoryV2(); genRep.StartTransaction(); User user = genRep.GetById<User>(UserID);...

How to get started with Visual studio 2012

c#,asp.net-mvc,asp.net-mvc-3,asp.net-mvc-4,visual-studio-2012
I want to create web application using Visual Studio 2012. The application should login into a website and report numerical findings on the UI. The language used will be Visual C#. I have loaded the application and selected on the menu: File> New > Projects. A window appears with multiple...

How to add an Option label on ListBoxFor HTML Helper in ASP.Net MVC

asp.net-mvc,asp.net-mvc-4,html-helper
How can I add an option label like the one existent on the DropDownListFor for a ListBoxFor HTML Helper ? I have the code similar to bellow: <%= Html.ListBoxFor( m => m.SelectedElements, new MultiSelectList(Model.AllPossibleElements, "ID", "Text")) %> And the image bellow is the output: I would like to have a...

ASP .Net MVC get decorated roles for unathorized request

c#,asp.net,asp.net-mvc,asp.net-mvc-4
In MVC we decorate actions using AuthorizeAttribute. When a given user is not authorized for a particular action it calls HandleUnauthorizedRequest method. I have overridden this method in my custom class called CustomAuthorizeAttribute that inherits from AuthorizeAttribute. With in the scope of my overridden HandleUnauthorizedRequest method how do I get...

Add XElement dynamically using loop in MVC 4?

c#,xml,asp.net-mvc-4,for-loop
i will like to add the Xelement in Xdocument but how can i add in dynamically using loop? I need to capture the user multiple answer and generate the Xelement dynamically. Please guide me or provide any hint. Thanks alot! [HttpPost] public ActionResult SURV_Answer_Submit(List<AnswerQuestionViewModel> viewmodel, int Survey_ID, string Language) {...

Binding data to TextBox without showing text

asp.net,asp.net-mvc,asp.net-mvc-4
When binding text/data to a TextBox, it is done like @Html.TextAreaFor(model=> model.Question) but, when the PostBack happens, the text shows up in the TextBox. Is there a way to still bind the data to the textbox, but not display the text in the textbox? I have a search functionality on...

How Can ignore @ in Pattern in MVC

asp.net-mvc-4
I want write pattern to my textbox in view this textbox will hold email value but i want write RegEx but i received error because RegEx contains @ i wrote @@ but still doesn't work My Code <input type="text" name="Emails" id="Emails" class="form-control Div-heigh" placeholder="To...." required pattern="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?" /> ...

Why does my MVC binding stop working when I assign a nested model to a variable?

c#,asp.net-mvc,asp.net-mvc-4,razor
I have code something like this contrived example in my MVC 4 razor view: @for (int i = 0; i < Model.NestedModel.Count; i++) { @Html.HiddenFor(model => modelModel.NestedModel[i].Id) @Html.EditorFor(model => Model.NestedModel[i].SomeProperty) } In which case everything works fine for me However, I wanted to tidy this up a little as the...

Set JQuery propeties to Image folder path in img src tag

javascript,jquery,html,image,asp.net-mvc-4
Question background: I'm trying to set two propeties of a JQuery function to an img src who's images are stored in the Images folder of my MVC site. The Issue: The following code shows the properties nextText and prevText being set to a left and right .jpg I have in...

MVC best practice for displaying static generated data

c#,asp.net-mvc,asp.net-mvc-4,razor
Question background: I have a two page MVC 4 web app. The first page's view currently has its data manually typed into the View as its static i.e nothing is being passed to the View from its associated Controller method, as shown: Index controller method: Public ActionResult Index() { return...

Need to Close the div in if condition MVC View

asp.net-mvc,asp.net-mvc-4
I am trying to close a div inside the if condition which is inside a foreach loop. @foreach (var item in ViewBag.modal) { counter++; <div class="Class1"> <div class="span6"> <!-- block --> <div class="block"> <div class="block-header"> <div class="left"> @item["Topic"];</div> </div> <div class="collapsein"> @item["Desc"];</div> </div> </div> @if (counter % 2 == 0)...

Setting up routing when RemoteAttribute specifies AdditionalFields

c#,asp.net,asp.net-mvc,asp.net-mvc-4
How to configure actions if I specify AdditionalFields for validation via RemoteAttribute to handle possible optional additional fields? Currently I try to have actions for possible combinations of optional fields and it does not work as show below. I have a form that is bound to a model and one...

select random data from database in mvc4 C#

c#,asp.net-mvc-4
I have database. Actually,i am doing for it display 10 image newest from my database but i want to display random 10 image from database.How can i do it? public ActionResult Details(int id) { var products = db.TblProductImages.Include(t => t.TblProduct); ViewData["viewcategory"] = (from p in products orderby p.ProductID descending select...

Custom Data Annotation and MVC Helper

c#,asp.net-mvc,asp.net-mvc-4
I want to expose a globalized help text on to an MVC view. Currently the code looks like this, Custom attribute class class HelpTextAttribute : Attribute { public string Text { get; set; } } View model property and custom annotation [HelpText(Text = "This is the help text for member...

Send a parameter from an action to a view

asp.net-mvc,asp.net-mvc-4
I want to send a parameter to a view from an action that resolves and sends that value. The issue is that when the parameter "arrives" to the view, it arrives null giving me an error when I try to manage it. The code I have in the action is...

get roles attribute of controller in OnActionExecuting in mvc

c#,asp.net-mvc,asp.net-mvc-4,actionfilterattribute
I want to read the filter attributes of controller in OnActionExecuting method. for this I have written this code but this empty array. public class BaseController : Controller { protected override void OnActionExecuting(ActionExecutingContext filterContext) { var getActionName = filterContext.ActionDescriptor.ActionName; var getControllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName; var getUserName = User.Identity.Name; var getUserRoles =...

Exact need of jquery.validate.js

jquery,asp.net-mvc-4,jquery-validate
I am working in Mvc4. Creating client side validation using jquery. I have created a view. But the validation still working without the validate.js file. May be the uses will be in another way. Can someone please explain me what and how the validate.js file will be used to implement...

Form Post Not working While Submission

c#,asp.net,asp.net-mvc,asp.net-mvc-4
Whenever I try to post my form I get the following error: An error occurred while getting provider information from the database. This can be caused by Entity Framework using an incorrect connection string. Check the inner exceptions for details and ensure that the connection string is correct. public class...

How to consume multipart/form data request in C# mvc 4 webservice

c#,asp.net-mvc,web-services,wcf,asp.net-mvc-4
I created a web service for file upload. When I call this webservice I can't find multipart-form data request. If I call this webservice without a file then it will working fine. My code is: Interface code: [OperationContract] [WebInvoke(RequestFormat = WebMessageFormat.Json, Method = "POST", ResponseFormat = WebMessageFormat.Json, UriTemplate = "/GetStream")]...

Rendering “~/bundles/jqueryval”

c#,asp.net-mvc,asp.net-mvc-4,razor
I need your help, I have written this code to render the "~/bundles/jqueryval" The view Code @model workflow.DataHolders.NewCompany <link href="@Url.Content("~/sharedfiles/css/forms/addnew.css")" rel="stylesheet" type="text/css" /> <div id="Add_container"> @if (!ViewData.ModelState.IsValid) { <div id="validationMessage">Please Correct The Errors Below</div> } @using (Html.BeginForm("ValidateAndSignUp", "Accounts", FormMethod.Post)) { @Html.AntiForgeryToken() @Html.ValidationMessage("CompanyName"); <span...

NHibernate fluent mapping to an entity property

asp.net-mvc-4,nhibernate,fluent-nhibernate,nhibernate-mapping,fluent-nhibernate-mapping
I have a table called "Customers" and in this table there are store and office address. In the code there is a Customer class with two properties that are of type Address (one for StoreAddress and OfficeAddress). public class Customer { public virtual int Id { get; set;} public virtual...

MVC Hidden field via HTML Helper in Form Post issue

c#,asp.net,asp.net-mvc,asp.net-mvc-4,razor
I have an issue when using a hidden field in an MVC Form Post. When the hidden field is generated via a HTML Helper it won't preserve it's value during the postback. But when using a HTML tag, it works. Unfortunately this one has taken me a whole day to...

mvc - Html.BeginForm postbacks to wrong controller

asp.net-mvc-4,html.beginform
I'm facing a very annoying issue in my mvc 4 application. What I'm doing: I have a main view (Index) and a partial view added to main view. on partial view a form is added to post data to the action in some controller but, it posts to Home controller...

How would I link to an external site from a cell in a kendo grid?

c#,asp.net-mvc-4,kendo-ui,kendo-grid
Just like the title says. I want to have a kendo grid with a column called Link. That column would need to dynamically generate a link to whatever address the user puts into it. I don't need to worry about error checking to ensure the link is valid, or anything...

How to run javascript function in Razor MVC .net

javascript,asp.net-mvc,asp.net-mvc-4,razor
<script type="text/javascript"> @if (@Model.Invoice.InvoiceDate != null) { <text> function UTCToLocalTime(date) { var time = new Date(Date.parse(date)); var timeOffset = -((new Date()).getTimezoneOffset() / 60); time.setHours(d.getHours() + timeOffset); return time; } var date = @Model.Invoice.InvoiceDate UTCToLocalTime(date); </text> } </script> I am printing the above invoice and its open in a window....

how to forward a link with URI to another link with the same URI

html,asp.net,html5,asp.net-mvc-4,asp.net-web-api-routing
My program directs users to a webpage with their username and password. E.g. http://example.html?username=username&password=password. Now I created another page in asp.net and I want some code on example.html to redirect the link to http://example.aspx?username=username&password=password. So what i want is to get the URI from the first url and direct it...

ApplicationUser ICollection member not being saved in DB

c#,.net,entity-framework,asp.net-mvc-4,asp.net-mvc-5
I've added some properties to ApplicationUser, and two of them are ICollection's. When I use Update-Database it doesn't generate columns for these two members. So, what am I missing here? I imagine it's very basic. I'm used to working with Hibernate in Java, where it generates a new table for...

mvc 4 custom format validator does not show error and allows the form to submit

asp.net-mvc,validation,asp.net-mvc-4
I have the following validator for a MVC 4 view public class IpFormatValidator: ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { ValidationResult resp; if (value != null) { string ip ; IPAddress noUsed ; ip = value.ToString(); if(IPAddress.TryParse(ip, out noUsed)) { resp = ValidationResult.Success; } else { resp...

Setting up IdentityServer wtih Asp.Net MVC Application

c#,asp.net-mvc-4,identityserver3
I apologize in advance for asking this as I have next to no knowledge of security in general and IdentityServer in particular. I am trying to set up IdentityServer to manage security for an Asp.Net MVC application. I am following the tutorial on their website: Asp.Net MVC with IdentityServer However,...

Protractor, login to asp,net MVC login page, wait for default page then , redirect to angular page and do tests…how?

c#,angularjs,asp.net-mvc-4,selenium,protractor
I'm trying to implement Protractor test on my MVC Project that we are slowly converting to Angular I login on a MVC login page, enter the login and password, Click login, then I need to wait for the login to go through several pages, and get to the default screen....

How to download a file through ajax request in asp.net MVC 4

jquery,json,asp.net-mvc-4,asp.net-ajax
Below is my code : public ActionResult DownloadAttachment(student st) { var file = db.EmailAttachmentReceived.FirstOrDefault(x => x.LisaId == st.Lisaid); byte[] fileBytes = System.IO.File.ReadAllBytes(file.Filepath); return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, file.Filename); } This is the script which i'm using $(function () { $("#DownloadAttachment").click(function () { $.ajax( { url: '@Url.Action("DownloadAttachment", "PostDetail")', contentType: 'application/json; charset=utf-8', datatype: 'json',...

Jquery: Change contents of