dimanche 10 mai 2015

Using [Authorize] on the GET and POST methods with same name

Maybe the answer to the following is simple, but I have hard time finding the answer:

When I have a GET method in a controller that is secured with the [Authorize] attribute, and a POST method (defined with [HttpPost]), will the same restrictions apply to it as well? Both methods have the same name, but differ in parameters.

Example code:

 [Authorize(Roles = "Administrator")]
 public ActionResult Delete()
 {
     return View();
 }

 [HttpPost]
 public ActionResult Delete(int id)
 {            
     /* the method's logic omitted */
     return RedirectToAction("Index");
 }

Using AddRange with Distinct() is not working with Enum in MVC5 C#

I am trying to filter one of my enum fields from my model. Here's the definition of my enum:

public enum ProjectDifficulty
{
    Medium,
    High,
    [Display(Name = "Very High")]
    VeryHigh,
    Complex
}

But I cannot get the results; I see this error:

Cannot convert from 'System.Linq.IQueryable<Finder.Models.ProjectDifficulty>' to 'System.Collections.Generic.IEnumerable<string>'

My controller contains this code:

var ProjectDifficultyLst = new List<string>();

var ProjectDifficultyQry = from b in db.Projects
                           orderby b.ProjectDifficulty
                           select b.ProjectDifficulty;

ProjectDifficultyLst.AddRange(ProjectDifficultyQry.Distinct());

ViewBag.projectDifficulty = new SelectList(ProjectDifficultyLst);

if (!String.IsNullOrEmpty(projectDifficulty))
{
    SearchQry = SearchQry.Where(l => l.ProjectDifficulty == projectDifficulty);
}

Update MVC from 4.0 to 5.2 - Could not install package

Im trying to update my project from MVC 4.0 to 5.2. But As soon I do that I get an error message:

Install-Package : Could not install package 'Microsoft.AspNet.Razor 3.2.3'. You are trying to install this packag e into a project that targets '.NETFramework,Version=v4.0', but the package does not contain any assembly referen ces or content files that are compatible with that framework. For more information, contact the package author. At line:1 char:1 + Install-Package Microsoft.AspNet.Mvc -Version 5.2.3 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

How can I Sovle this issue? And What does this mean?

Fully center a div inside a div with bootstrap and Visual Studio's shared layout

I am using Bootstrap and Visual Studio to make a portal webpage. I want a div centered on the page (with a background color). Then I want a div inside that div, again fully centered (this will be the login form).

Right now I'm using the grid system with 3 columns to get the middle of the page (horizontal centered). But the thing is that the first div isn't centered either.

Can someone explain me how to center a div horizontal and vertical, and then another div inside there fully centered.

I am using VS's shared layout, so where exactly do I need to put the Renderbody? In the first div or second div?

Thanks in advance.

Code I am currently using:

HTML of the shared layout:

<html xmlns="http://ift.tt/lH0Osb" style="height: 100%;">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>@ViewBag.Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="../../Content/themes/bootstrap.css">
    <link rel="stylesheet" href="../../Content/themes/stylesheet.css">
    <script src="http://ift.tt/1qRgvOJ"></script>
    <script src="http://ift.tt/1Cqnml8"></script>
</head>

<body style="height: 100%; background:#000;">
    @RenderBody()
</body>
</html>

The view file:

<div class="vertical-center" style="height:100%; background-color:aliceblue; background-position:center;background-repeat:no-repeat;">
    <div class="row">
        <div class="col-sm-4"></div>
        <div class="col-sm-4" style="background-color:lavenderblush;">
            @using (Html.BeginForm("Login", "Account"))
            {
                <span style="color:red">@ViewBag.Message</span>
                <fieldset class="vertical-center">
                    <ol>
                        <li>
                            @Html.TextBoxFor(m => m.Nickname)
                        </li>
                        <li>
                            @Html.PasswordFor(m => m.Password)
                        </li>
                    </ol>
                    <input type="submit" value="Log in" />
                </fieldset>
            }
        </div>
        <div class="col-sm-4"></div>
    </div>
</div>

And then the customized stylesheet.css:

.vertical-center {
  min-height: 100%;
  min-height: 100vh;
  display: flexbox;
  align-items: center;
  justify-content: center;
  flex-direction: column;
}
.vcenter {
    display: inline-block;
    vertical-align: middle;
    float: none;
}

Linq in controller MVC

In my application I am using Entity Framework.I need to show all available rooms at the moment. I have two tables room and reservation . They are connected many to many from table RoomReservation.

public class Room
    {
public int Id { get; set; }
public double CostNight { get; set; }
public virtual ICollection<Reservation> Reservation { get; set; }
}

public class Reservation
    {
public int Id { get; set; }
public string DateOfEntry { get; set; }
public int NumberOfNights { get; set; }
public virtual ICollection<Room> Room { get; set; }
}

I tried to write:

public IEnumerable<Room> GetRooms(int title, DateTime? datepicker)
        {
            return context.Room.Where(x => x.Booking.Count == 0 ||
            x.Booking.All(b => b.DateOfEntry > datepicker || (b.DateOfEntry < DbFunctions.AddDays(datepicker, b.NumberOfNights))))
            .Where(x=>x.Categoryid == title);
        }

datepicker - date selected by the Client. title - category room(this i need too). DateOfEntry - date of arrival in the Room. But it does not work.

Also, if for example the client chose 2015-05-10 and book for 5 days, and the database is already have booked this number 2015-05-12 , need display a message..how to do it?Thanks!

the model in view could not bind to the action in the controller in ASP.NET MVC4

I have defined the custom name about the input tag in Index view of Account. The name is iptloginPassWord and iptloginPassWord. However, in the controller the model will be null whenever the submit button is clicked.

I have attached the code below. Is this a model binding issue? Could you guys help to determine what is wrong here?

View:

<div class="rl-modal-body">
    <div class="login-model-body-wrap">
        @using (Html.BeginForm("Logon", "Account", FormMethod.Post, new { id = "loginForm" }))
        {
            <div class="rlf-model-group">
                <div class="ipt-container">
                    <div class="ipt-config ipt-UserName"></div>
                    @*h5提供了required属性,Name的N必须为大写*@
                    @*<input id="iptloginUserName" type="text" name="iptloginUserName" value="" placeholder="请输入用户名" class="ipt ipt-login" required="required" />*@
                    @Html.TextBoxFor(model => model.UserName, new { @id = "iptloginUserName", @Name = "iptloginUserName", @placeholder = "请输入用户名", @class = "ipt ipt-login", @required = "required" })
                </div>
                <p class="rl-p"></p>
            </div>
            <div class="rlf-model-group">
                <div class="ipt-container">
                    <div class="ipt-config ipt-Password"></div>
                    @*<input id="iptloginPassWord" type="password" name="iptloginPassWord" value="" placeholder="请输入密码" class="ipt ipt-login ipt-passwordforJS" required="required" />*@
                    @Html.PasswordFor(model => model.Password, new { @id = "iptloginPassWord", @Name = "iptloginPassWord", @placeholder = "请输入密码", @class = "ipt ipt-login ipt-passwordforJS", @required = "required" })
                </div>
                <p class="rl-p"></p>
            </div>
            <div class="rlf-model-group">
                <label for="AutoLogin">
                    <input id="AutoLogin" type="checkbox" checked="checked" />自动登录
                </label>
            </div>
            <div class="rlf-model-group">
                <p class="rl-p"></p>
                <input id="iptloginsubmit" type="submit" name="Button" value="登录" class="btn-red btn-full" />
            </div>
        }
    </div>
</div>


Controller:
public class AccountController : Controller
{
    //
    // GET: /Account/

    [AllowAnonymous]
    public ActionResult Index()
    {
        return View();
    }

    [AllowAnonymous]
    [HttpPost]
    public ActionResult Logon(User model)
    {
        string username = model.UserName;//this will get null 
        string password = model.Password;//this will also get null
        return View(model);
    }
}

How to programaticaly enable/disable control in razor view [closed]

I need to enable/disable certain controls in the view depending on a condition. I try to use the answer in this link here but it did not work in my case. Currently I'm using the (pseudo) code as show below, which works, but it is insane to use it, since there are many entries like that. I need a solution like the one in here

@{ if (Model.ChargeCost == true)
 {
   @Html.TextBoxFor(m => m.Cost, new { @id="myId", @class = "form-control" })
 }
  else
 {
   @Html.TextBoxFor(m => m.Cost, new { @id = "myId", @class = "form-control", disabled = "disabled" })
}

UPDATE: I APOLOGIZE FOR THE MISUNDERSTANDING BUT THE CODE THAT I HAVE AS AN EXAMPLE WORKS PERFECTLY. WHAT I NEED IS SOMEONE WHO ACTUALLY HAS A DEEPER UNDERSTANDING OF MVC5 AND C# THAT CAN OPTIMIZE THIS TERRIBLE CODE, SINCE I HAVE MANY MORE CONDITIONS LIKE THIS ONE IN THE VIEW..