I am trying to add a master page in my asp.net web app . But after i choose add new item i am not able to find master page to create one.Thanks in advance

So I have two models with a one to many relationship. Callout, and shift offer. Callout can have many shift offers.

I want to pass my callout_id to the shift-offer controller. I've done this by modifying the Index() method as follows:

    public async Task<ActionResult> Index(long? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            Debug.WriteLine("Callout ID cannot be null");
        }
        var shift_Offers = db.Shift_Offers.Where(s => s.callout_id_fk == id);
        return View(await shift_Offers.ToListAsync());
    }

I've also modified one of my HTML action links to call a different page:

@Html.ActionLink("View Callout", 
                "Index", 
                "ShiftOffer", 
                new { area = ""}, 
                new { id=item.callout_id_pk }) |

But here's the kicker, when I try to call Index(long id), it's throwing that bad request error. Why isn't my ID being passed like it is with the default scaffolded links?

I want to try same this = Submit form using AJAX in Asp.Net mvc 4

<script src="~/Scripts/jquery-1.8.2.min.js"></script>    
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>   


@using (Ajax.BeginForm("SaveData", new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dane"
}))

I can't use Ajax , AjaxOptions and InsertionMode in razor page(.cshtml)

{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>
    <legend>Details</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.Name)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.Email)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.Email)
        @Html.ValidationMessageFor(model => model.Email)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>
</fieldset>
}

I have a strange problem with our ASP.NET web application in Microsoft Edge.

When clicking a button, the click event was called twice also the page init and pag load. The button has handles btn.ServerClick This only happens on Microsoft Edge. Other browsers like Chrome, IE8/IE11 are working okay.

Did any of you experience similar problem? What causes the problem and how did you able to fix this?

So I'm net to ASP.net MVC, but not new to C#. I've linked in my project with the data source, and it's created all of my Create Read Update Delete methods and views. Great. Now I need to customize some things.

First thing, I need to upload a .csv file, this is what will populate one of our models, as a stopgap while we migrate from an old pen-and-paper system.

Here's postback method that get's called when the submit button gets pressed:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "callout_id_pk,start_timestamp,drivers_license_needed,med_training_needed,worksite_code_fk,shift_notes,status,job_class_code_fk,worksite_name,job_class_name,gender_req")] Callout callout)
        {
            Debug.WriteLine("THIS LINE OF CODE RAN?");
            if (ModelState.IsValid)
            {
                db.Callouts.Add(callout);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }


            foreach (string upload in Request.Files)
            {
                if (Request.Files[upload].ContentLength == 0) continue;
                string pathToSave = Server.MapPath("~/App_Data/UploadedFiles");
                string filename = Path.GetFileName(Request.Files[upload].FileName);
                Request.Files[upload].SaveAs(Path.Combine(pathToSave, filename));
            }

            ViewBag.worksite_code_fk = new SelectList(db.Worksites, "worksite_code_pk", "worksite_name", callout.worksite_code_fk);
            return View(callout);
        }

And here's the view, with the non-pertinent controls removed for readability.

@using (Html.BeginForm("Create", "Callouts", FormMethod.Post, new {enctype="multipart/form-data"})) 
{
    @Html.AntiForgeryToken()


        <!--@Html.ValidationSummary(true, "", new { @class = "text-danger" })-->

        <div class="form-group">
            <input type="file" name="FileUpload1" /><br />
        </div>

        <!-- other form controls here -->

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
}

Now, for some reason in the postback, Request.Files is not seeing any files posted back. What am I missing here? Note that for now, I'm just trying to save the file to disk. But in the end, the file will be read and used to populate the model.

I'm coding in Visual Studio 2015. I have a basic (non-MVC) Razor webpage, but am converting it to MVC. I have taken apart the large default.vbhtml page and created several partials. Now I have a layout that calls:

<!--HTML Code Here-->
@RenderPage("_header.vbhtml)
@RenderPage("_sidebar.vbhtml")
<!--HTML Code Here-->
@RenderBody() 
<!--HTML Code Here-->

The index.vbhtml page called by the @RenderBody also pulls in partials (3 of them).

I have some base code (in the original single-page site) that pulls in variables that I use throughout that page and which would be used in each of the partials. That code is:

@Code

Dim webServer as string
Dim reportsServer as string
Dim plantName As String
Dim machineName = Server.MachineName
Select Case Left(machineName, 2)
    Case "P1"
        plantName = "P1 North"
        webServer = "P1N0101"
    Case "P2"
        plantName = "P2 South"
        webServer = "P2S0101"
    Case Else
        plantName = "P5"
        webServer = "P5101"
End Select
Dim ppaDepartments As Database
ppaDepartments = Database.Open("PPA-DB")

Dim ppaLines As Database
ppaLines = Database.Open("PPA-DB")

Dim selectQueryString As String = "Select * from Departments where Tag='" & plantName & "'"
End Code

I am using all of those variables throughout the view and partials. How would I globalize these variables so that I can reference them in each of the partials properly?

This seems like it should be built in, at least as an option. I'm using Forms Authentication with the ASP.net Membership provider.

I want to force a user to re-authenticate when their password is updated, on all clients where he or she is logged in. In other words, I want to invalidate all auth tickets (cookies) that were created before the password change.

Any recommendations on how to do this safely, in particular in an ASP.net MVC 5 web application?

once i try to login and login failed due to wrong user name password but after login failed i try to login then its say anti forgery token was meant for a different claims based user than the current user and my session expires randomly at any time after session expire when refresh the page it shows login page then i try login with correct credentials then its says anti forgery token was meant for a different claims based user than the current user

my session timeout is 2400 minuts in web.config and 1 day in identity

I have a web control which requires it's own javascript so it uses RegisterClientScriptResource called from OnPreRender to render a script tag when the page renders.

The web controls javascript depends on jquery. However to allow for different versions of jquery it does not embed the jquery javascript itself. Instead it relies on the web application to reference the appropriate jquery script. So to do that My page has a ScriptManagerProxy with a ScriptReference to the jquery js file.

When the page renders, I get a script tag referencing the web controls script followed by a script tag referencing the jquery file:

<script src="/MyApp/ScriptResource.axd?d=D9drwtSJ4hBA...qGfE1&amp;t=ffffffffc7ae6e38" type="text/javascript"></script>
<script src="Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.11.1.min.js" type="text/javascript"></script>

My problem is the order of script includes needs to be reversed because it extends jquery:

jQuery.extend(jQuery.ui, { mydatepicker: { version: "1.0.0"} }); jQuery.fn.mydatepicker = function (options) {

...

}

The current order causes my mydatepicker function to not work.

If I use ScriptManager or ScriptManagerProxy in my page asp.net will render script references in order of hierarchy, so master page script references render first followed by references in it's children then their children all the way down the chain. I would have expected that the script reference in my web control would render after the others given that the control is the deepest within the hierarchy, but instead it renders first.

I begin with ASP.NET and I have a problem with authentication.

This is the code:

web.config

<system.web>
  <authentication mode="Forms">
    <forms loginUrl="~/users/login" timeout="3000"  />
  </authentication>
  <compilation debug="true" targetFramework="4.5.2" />
  <httpRuntime targetFramework="4.5.2" />
</system.web>

login

public ActionResult login()
{
    if (Request.HttpMethod == "POST")
    {
        if (Request.Form["email"] == null || Request.Form["password"] == null)
            ViewData["error"] = "form_error";
        else
        {
            User user = this.dal.authUser(
            Request.Form["email"],
            Request.Form["password"]);
            if (user == null)
                ViewData["error"] = "auth_error";
            else
            {
                FormsAuthentication.SetAuthCookie(user.id.ToString(), false);
                return Redirect("/profiles/" + user.id);
            }
        }
    }
    return (View());
}

profile controller

[HttpGet]
public ActionResult get(int id)
{
    ViewData["auth"] = false;
    if (HttpContext.User.Identity.IsAuthenticated)
        ViewData["auth"] = true;
    Response.Write(HttpContext.User.Identity.Name);
    Profile profile = this.dal.getProfile(id);
    if (profile == null)
        return View("~/Views/error404.cshtml");
    ViewData["profile"] = profile;
    return View();
}

and View for get a profile

@using Plume.Areas.Users.Models;

@{
    Layout = "~/Views/Layout/layout.cshtml";
    Variables.pageTitle = "Profil";
    Profile profile = (Profile)ViewData["profile"];
    bool auth = (bool)ViewData["auth"];
}

@{ 
    if (auth)
    {
        <h1>Auth</h1>
    }
}

<p>
    ceci est le profil de : 
    @profile.username
    <br />
    dont l'email est :
    @profile.user.email
</p>

So, when I log, a cookie called .ASPXAUTH is returned, but in the view for a profile, the h1 isn't displayed.

What is not correct?

There is a set of records with a created date field in a table. How do I select all the records that were created on a given day of the week. e.g. all records that were created on a Monday, it could be this Monday, last Monday or the Monday before.

This is what I have written so far:

from ob in obList
where SqlFunctions.DateDiff("days", today, ob.StartDate) % 7 == 0
select ob.CustomerOnboardingId

But I get an error on this:

{"This function can only be invoked from LINQ to Entities."}

Update 1:

obList is a collection in memory. And today is variable that holds DateTime.Today;

I have a website in which I had originally setup a default webforms project. Visual studio was nice enough to include some things I didn't really want. I later on updated the website and removed the below functionality(URL Routing). The issue I am experiencing is client's connecting to the website using the same URL as before are getting a 404 error. I found in the IIS log that the request didn't have the .aspx extension if they had visited the page before. The clients are using google chrome so I don't know if its all browsers with this issue. Asking the clients to clear browser cache has fixed the problem. I've been searching for an eloquent way of fixing the problem on client computers with out asking everyone to clear browser cache but I haven't found anything yet. Does anyone have any suggestions on how to fix the problem?

Here is what I've come up with so far:

  1. Change the URL of the website - not desirable since its a request form and the URL is already familiar to them.
  2. Custom error page for the 404 with instructions on clearing the cache - not a very friendly user experience
  3. Setup routing again on the website - I rather not cause I don't see a need with it being a web forms project

Any advice would be greatly appreciated!

Global.asax.cs

    void Application_Start(object sender, EventArgs e)
    {
        // Code that runs on application startup
        RouteConfig.RegisterRoutes(RouteTable.Routes);
    }

RouteConfig.cs

    public static void RegisterRoutes(RouteCollection routes)
    {
        var settings = new FriendlyUrlSettings();
        settings.AutoRedirectMode = RedirectMode.Permanent;
        routes.EnableFriendlyUrls(settings);
    }

IIS Log:

    cs-method cs-uri-stem cs-uri-query s-port sc-status sc-substatus sc-win32-status
    GET /example/Review.aspx id=7190 80 200 0 0 
    GET /example/Review id=7174 80 404 0 2 

We have an ASPxHtmlEditor control which we've configured to upload to a CDN.

This works for most of our needs but in some cases, the CDN lags and the image isn't available right away.

The ASPxHtmlEditor control gets the correct path from the upload process, but the image isn't available yet. The image returns as a 404 and a broken image appears in the editor.

The image becomes available shortly after upload, and once the editor is re-rendered by some action from the user, the image appears.

Is there some way to prepare ASPxHtmlEditor for lag from the image server?

My ASP.NET web application is running in IIS. Sometimes I am unable to debug it and the JIT debugging commands (Debugger.Launch() and Debugger.Break()) do not work.

When this happens, I can use Debug / "Attach to Process" in VS 2015 and the w3wp.exe process is listed with a type x64 rather than the usual Managed (v4.0.30319), x64.

How is this possible, and how do I fix it?

I am building in Debug mode, and the web.config has

<compilation debug="true" targetFramework="4.5.2" />

All the settings I can find in the project and IIS are the same as dozens of other projects that all work fine.

So I'm net to ASP.net MVC, but not new to C#. I've linked in my project with the data source, and it's created all of my Create Read Update Delete methods and views. Great. Now I need to customize some things.

First thing, I need to upload a .csv file, this is what will populate one of our models, as a stopgap while we migrate from an old pen-and-paper system.

Here's postback method that get's called when the submit button gets pressed:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "callout_id_pk,start_timestamp,drivers_license_needed,med_training_needed,worksite_code_fk,shift_notes,status,job_class_code_fk,worksite_name,job_class_name,gender_req")] Callout callout)
        {
            Debug.WriteLine("THIS LINE OF CODE RAN?");
            if (ModelState.IsValid)
            {
                db.Callouts.Add(callout);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }


            foreach (string upload in Request.Files)
            {
                if (Request.Files[upload].ContentLength == 0) continue;
                string pathToSave = Server.MapPath("~/App_Data/UploadedFiles");
                string filename = Path.GetFileName(Request.Files[upload].FileName);
                Request.Files[upload].SaveAs(Path.Combine(pathToSave, filename));
            }

            ViewBag.worksite_code_fk = new SelectList(db.Worksites, "worksite_code_pk", "worksite_name", callout.worksite_code_fk);
            return View(callout);
        }

And here's the view, with the non-pertinent controls removed for readability.

@using (Html.BeginForm("Create", "Callouts", FormMethod.Post, new {enctype="multipart/form-data"})) 
{
    @Html.AntiForgeryToken()


        <!--@Html.ValidationSummary(true, "", new { @class = "text-danger" })-->

        <div class="form-group">
            <input type="file" name="FileUpload1" /><br />
        </div>

        <!-- other form controls here -->

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
}

Now, for some reason in the postback, Request.Files is not seeing any files posted back. What am I missing here? Note that for now, I'm just trying to save the file to disk. But in the end, the file will be read and used to populate the model.

I have a problem regarding all of my Projects when trying to Debug .cshtml files when the application is hosted on a local IIS.

I always get the Message that the symbols aren't loaded:

enter image description here

Debugging the controller works fine though.

When debugging the application with IIS Express everything works as expected.

Here is how my Application is configured:

enter image description here

Every help is appreciated, because i am starting to freak out over that problem...

Edit: I am using VS 2015 Enterprise and IIS 7.5

<div class="spinner">
<div class="bounce1"></div>
<div class="bounce2"></div>
<div class="bounce3"></div>
</div>

How can i disable class spinner (css class) in Razor page?

I import in another page (index.cshtml)

<link href="@Url.Content("~/css/mixin/spinner.css")" rel="stylesheet" type="text/css" />

and _Layout.cshtml

@RenderSection("Styles", required: false)

but class spinner it's show in Login.cshtml without import. How can i disable in component or razor page ?

I have a link displayed on the page as:

@Html.ActionLink(
    "Buy",
    "Buy",
     new { id = item.ProductID, quantity },
     new { @onclick = "getQuantity()" }
)

Now, when a user clicks the Buy link, a Java Script pop-up should be shown where he can enter the quantity of purchase.

I need to check if the entered quantity is a positive number or not.

If not, I should stay on the same page and prompt the user to enter a positive value.

If yes, I should validate the stock availability and make transaction (this I will be handling inside the action in redirected controller.)

The action Buy takes two parameters, Id and Quantity,

public ActionResult Buy(int id, int amount)
{
    // code here
}

Here is the Java Script code which I found in the answer(modified a bit ) :How can I access Session variables and set them in javascript? But, this doesn't work.

<script>
    function getQuantity() {
        var qty = parseInt(prompt("Enter quantity: ", "1"));
        if (qty > 0) {
              '<%Session["Qty"] = "' + qty + '"; %>';
        }
        alert("Enter valid quantity!");
    }
</script>

How can I pass the value obtained in Java Script as one of the parameters to a action inside a controller? And how do I pass them in this case?

I've an Hotel model and there is a HotelPrice list in the model.

What i'm trying to do is when user display hotel detail page let hotel prices' info be shown, also they can be editable. I've a breakfastIncluded property on HotelPrice instances which i have to display as radio button.

Here is my code:

<div>
@{
foreach(var hotelPrice in Model.HotelPrices)
{
    <label class="mt-radio-inline>
        @Html.RadioButtonFor(hotelModel => hotelPrice.breakfastIncluded, "1", new { @checked = (hotelPrice.Breakfast.ToString() == "1") })Yes
        <span></span>
    </label>
    <label class="mt-radio-inline>
        @Html.RadioButtonFor(hotelModel => hotelPrice.breakfastIncluded, "0", new { @checked = (hotelPrice.Breakfast.ToString() == "0") })No
        <span></span>
    </label>
}
}

When i display my page(i could not come editing part, yet), all breakfastIncluded properties' radio buttons are displayed as unassigned and the last one's radio button is displayed wrongly(i.e it has to be "Yes" but it seems like "No").

However, when i checked by Inspect tool of browser, all of the radio buttons' checked property appears correct(i.e if it should be "Yes" that radio button's checked is true and "No"'s checked is false).

I'm new to html and i could not figure out why that happens. Can you help me? Thanks in advance.

I have the following Grid:

@(Html.Kendo().Grid<Forms.ViewModels.TestFormViewModel>()
.Name("gridForms")
.ToolBar(commands =>
{
commands.Template(
    @<Text>
    <b class="FloatRight SearchTopMarginExtra">Search: </b>
    <input type="search" id="searchbox" class="SearchRight SearchTopMargin form-control k-textbox" />
    </Text>);
})
.Columns(columns =>
{
    columns.Bound(p => p.Code).Filterable(true).Width(175);
    columns.Bound(p => p.LiveDate).Format("{0:" + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + "}").Width(110);
    columns.Bound(p => p.EndDate).Format("{0:" + System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern + "}").Width(110);
    columns.Command(command => { command.Edit(); command.Destroy(); }).Width(150);
    columns.Command(command => { command.Custom("Mappings Info").Click("viewMappings").SendDataKeys(true); }).Width(150);
})
.Editable(editable => editable
    .Mode(GridEditMode.PopUp)
    .TemplateName("FormGridEditor")
    .Window(w => w.Title("Edit Form Details")
    .Name("editFormWindow")
    .Width(500))
)
.Events(e => e.DataBound("onRowBound"))
.Reorderable(reorderable => reorderable.Columns(true))
.Resizable(resizable => resizable.Columns(true))
.Pageable()
.Sortable()
.Scrollable()
.Filterable()
.HtmlAttributes(new { style = "height:550px;" })
.DataSource(dataSource => dataSource
    .Ajax()
    .PageSize(20)
    .Events(events => events
        .RequestEnd("onRequestEnd")
        .Error("onError")
        )
    .Model(model => model.Id(p => p.FormId))
    .Read(read => read.Action("GetForms", "Forms").Type(HttpVerbs.Post))
    .Update(update => update.Action("UpdateForm", "Forms"))
    .Destroy(delete => delete.Action("DeleteForm", "Forms"))
 )

)

With the following onDataBound function:

function onDataBound(e) {
    var grid = $("#gridForms").data("kendoGrid");
    var gridData = grid.dataSource.view();

    for (var i = 0; i < gridData.length; i++) {
        var currentUid = gridData[i].uid;

        if (gridData[i].FormAssigned == false) {
            var currenRow = grid.table.find("tr[data-uid='" + currentUid + "']");
            var mappingButton = $(currenRow).find(".k-grid-MappingsInfo");
            mappingButton.hide();
        }
    }
}

The dataBound event is to hide the custom mapping button depending on the FormAssigned bool returned for each row.

This works fine locally but for some reason once it's deployed to IIS it will read the formAssigned bool as false no matter what without throwing any errors. So it will hide the button when it should be showing it for some rows.

It's definitely something happening in the front end as the services and API I have return all the data I expect once deployed.

Anyone have any ideas on where I should be looking next here?

This question already has an answer here:

I have model in which i define permission list which contains permission id and other permission like canView canUpdate and canDelete i want to pass true when check box is checked and also pass permission id in list and save it in database but permissionlist comes null MVC here is model and view code.

Register Admin View Model

public class RegisterAdminViewModel
{
    [Required(ErrorMessage = "Enter First Name")]
    [DisplayName("First Name")]
    public string FirstName { get; set; }
    [Required(ErrorMessage = "Enter Last Name")]
    [DisplayName("Last Name")]
    public string LastName { get; set; }
    [Required(ErrorMessage = "Enter Email Address")]
    [EmailAddress]
    [DisplayName("Email Address")]
    public string LoginEmail { get; set; }
    //list of permission View model
    public List<PermissionViewModel> PermissionList { get; set; } 
}

List of Permission View Model

public class PermissionViewModel
{
    public long UserId { get; set; }
    public long PermissionId { get; set; }
    public string PermissionName { get; set; }
    public bool CanView { get; set; }
    public bool CanUpdate { get; set; }
    public bool CanCreate { get; set; }
    public bool CanDelete { get; set; }
}

View

<div class="form-group">
    <div class="col-md-12">
        @foreach (var item in Model.PermissionList)
        {
            <div class="col-md-12 permissiondiv">
                <label class="checkbox">
                    <span class="icons"><span class="first-icon fa fa-square-o"></span><span class="second-icon fa fa-check-square-o"></span></span>
                    <input type="checkbox" value="@item.PermissionId" />
                    <strong>@Html.DisplayFor(model => item.PermissionName)</strong>
                </label>
            </div>
            <div class="col-md-12">
                <div class="col-lg-3">
                    <label class="checkbox">
                        <span class="icons"><span class="first-icon fa fa-square-o"></span><span class="second-icon fa fa-check-square-o"></span></span>
                        @Html.CheckBoxFor(model => item.CanView, new { @checked = "checked" })
                        <label>Can View</label>
                    </label>
                </div>
                <div class="col-lg-3">
                    <label class="checkbox">
                        <span class="icons"><span class="first-icon fa fa-square-o"></span><span class="second-icon fa fa-check-square-o"></span></span>
                        @Html.CheckBoxFor(model => item.CanCreate)
                        <label>Can Create</label>
                    </label>
                </div>
                <div class="col-lg-3">
                    <label class="checkbox">
                        <span class="icons"><span class="first-icon fa fa-square-o"></span><span class="second-icon fa fa-check-square-o"></span></span>
                        @Html.CheckBoxFor(model => item.CanUpdate)
                        <label>Can Update</label>
                    </label>
                </div>
                <div class="col-lg-3">
                    <label class="checkbox">
                        <span class="icons"><span class="first-icon fa fa-square-o"></span><span class="second-icon fa fa-check-square-o"></span></span>
                        @Html.CheckBoxFor(model => item.CanDelete)
                        <label>Can Delete</label>
                    </label>
                </div>
            </div>
        }
    </div>
</div>