Affichage des articles dont le libellé est Active questions tagged asp.net-mvc - Stack Overflow. Afficher tous les articles
Affichage des articles dont le libellé est Active questions tagged asp.net-mvc - Stack Overflow. Afficher tous les articles

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..

ASP.NET MVC5 EF6 Relation with ApplicationUser

[ForeignKey("Creator")]
public string CreatorID {get;set;}
public virtual ApplicationUser Creator {get;set;}

While update-database, errors appeared. Said there's no Key column for ApplicationUser, I've got information about modelBuilder, but I don't want to change anything inside the project and database, which project using Asp.net default authentication template and database column with AspNet prefix. Is there any ways to get there Thanks

Show live summation in Html Textbox helper

I'm trying to make a website using asp.net mvc 4 and jQuery 1.9.1 where user can get the summation automatically whenever typing to other textbox. But for some reason whenever I type to other textboxes I don't get any result in my Total textbox. Here are my codes,

<script>
    $(document).ready(function () {
        $('.toSum').each(function () {
            $(this).keyup(function () {
                var total = 0;
                $('.toSum').each(function () {
                    if (this.value.length != 0) {
                        total += parseInt(this.value);
                    }
                });
                $('#txtTotal').html(total);
            });
        });
    });
</script>
<div class="tab-pane" id="AddFl" style="padding-top: 10px; padding-left: 10px;">
            @using (Html.BeginForm("SumManager", "Home"))
            {
                @Html.ValidationSummary(true)
                <div class="editor-label">
                    <strong>Set Basic</strong>
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(a => a.Flats.basic, new { @class="toSum" })
                    @Html.ValidationMessageFor(a => a.Flats.basic)
                </div>
                <div class="editor-label">
                    <strong>Set Bill</strong>
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(a => a.Flats.bill, new { @class="toSum" })
                    @Html.ValidationMessageFor(a => a.Flats.bill)
                </div>
                <div class="editor-label">
                    <strong>Set Miscellaneous</strong>
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(a => a.Flats.misc, new { @class="toSum" })
                    @Html.ValidationMessageFor(a => a.Flats.misc)
                </div>
                <div class="editor-label">
                    <strong>Total</strong>
                </div>
                <div class="editor-field">
                    @Html.TextBoxFor(a => a.Flats.total, new { id="txtTotal"})
                    @Html.ValidationMessageFor(a => a.Flats.total)
                </div>                    
                <p><input type="submit" class="btn btn-info" value="Add" /></p>
            }
        </div>

Am I doing something wrong in my code? How can I get the summation result instantly whenever user types on other textboxes? Need this help badly. Tnx.

MVC 4 bundleconfig.cs files not including in layout.cshtml

BundleConfig.cs

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {

        bundles.Add(new StyleBundle("~/resources/css").Include("~/resources/css/reset.css", 
            "~/resources/css/style.css", "~/resources/css/invalid.css"));

        bundles.Add(new ScriptBundle("~/resources/scripts").Include("~/resources/scripts/jquery-1.3.2.min.js",

            "~/resources/scripts/simpla.jquery.configuration.js", "~/resources/scripts/facebox.js",
            "~/resources/scripts/jquery.wysiwyg.js"));
    }
}

Layout.cshtml

 @Styles.Render("~/resources/css")
 @Scripts.Render("~/resources/scripts")

What it renders in html

 <link href="/resources/css" rel="stylesheet"/>
<script src="/resources/scripts"></script>

Not including css and js file paths in html ??

Get DropDownListFor selected value in multiple model

I create multiple model

public class MultipleModel
{
    public Photo Photo { get; set; }
    public Room Room { get; set; }
}

for two different models:

public class Room
    {
        public int Id { get; set; }
        public string NumberRoom { get; set; }
        public virtual ICollection<Photo> Photo { get; set; }
    }
public class Photo
    {
        public int Id { get; set; }
        public string PhotoName { get; set; }
        public int Roomid { get; set; }
        public virtual Room Room { get; set; }
    }

On click Submit in my view i want upload image to the folder with the name from DropDownListFor selected item ( for example /images/2/, where 2=id from DropDownListFor) and add to database. How i can correctly send selected item from DropDownListFor using Html.BeginForm? My view:

@using Hotel.BusinessObject
@model MultipleModel
@using (Html.BeginForm("AddRoomImg", "Admin",
        FormMethod.Post, new { enctype = "multipart/form-data", id = Model.Room.Id}))
{
    <div>@Html.DropDownListFor(m=> m.Room.Id, ViewBag.roomlist as SelectList, "Select Room")</div>

    <input type="file" name="img" />
    <input type="submit" value="upload" />
}

And my controller, where Room.Id in formCollection is always=0 and int? id not works and return NULL

        public ActionResult AddRoomImg()
        {
            ViewBag.roomlist = new SelectList(db.Room, "Id", "NumberRoom");
            return View();
        }
        [HttpPost]
        public ActionResult AddRoomImg(FormCollection formCollection, int? id)
        {
            foreach (string item in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[item] as HttpPostedFileBase;
                if (file.ContentLength == 0)
                    continue;
                if (file.ContentLength > 0)
                {
                    ImageUpload imageUpload = new ImageUpload { Width = 600 };

                    ImageResult imageResult = imageUpload.RenameUploadFile(file);
                    if (imageResult.Success)
                    {
                        //TODO: write the filename to the db 
                    }
                    else
                    {
                        ViewBag.Error = imageResult.ErrorMessage;
                    }
                }
            }

Bind Images Only After Page Completely Load Like Flipcart

i need to bind all images only after page completely load, like flipcart asynchronous image binding . please any one help me how to use in MVC 4

Passing an enum as an annotation parameter and getting list of itens

I created a custom attribute, that will be used to define that the property is used in a DropDownList. So the code of attribute is this:

public class DropDownList : Attribute
    {

        public Type EnumType { get; set; }

        public DropDownList(Type type)
        {
            this.EnumType = type;

        }

    }

I can't pass the enum as paramater, i only could do this passing the type of enum, like this:

class TestViewModel{

[DropDownList(typeof(MyEnums.EnumTest)]
prop int MyProp {get; set;}

}

I have a HTML extension, that needs to work like this:

public HtmlString AddSelectFor<TValue>(Expression<Func<TModel, TValue>> expression){

       var memberExpression = expression.Body as MemberExpression;
       var attribute = memberExpression.Member.GetCustomAttributes(typeof(MyProj.Attributes.DropDownList), false).FirstOrDefault() as MyProj.Attributes.DropDownList;

       // HERE i need to get the list of enum itens
       var itens = Enum.GetValues(attribute.EnumType);

       return HtmlHelper.DropDownListFor(expression, list);
}

The problem is, i don't have the enum, i have only the type, because it needs to be generic. So i can't do the cast to create the list used on "HtmlHelper.DropDownListFor".

How can i do that? Thanks

How to set scroll position in MVC 4 when new page is loaded

In my MVC 4 Webapp one of the views is listing house objects, and to the right of every object the user has the possibility to change language. Let's say you are on the middle of the page Reading about an object and decides you want to change language. Then a new page is loaded which looks exactly the same, but with text now in the other language. The problem is that the new page starts from the beginning (of course since it's a new page), and I want the newly loaded page to have the same scroll position as the previous one.

To get a better understanding you can visit the site at http://www.lomahovi.com and then click on Accomodations. There you will see a link for every object where you can switch between English and Russian.

So if a client is looking at an object in English, and decides that he/she wants to switch to Russian I don't want the page to start at the beginning but instead it should be on the same object/position as it was in English, so that the client doesn't have to scroll down the page to find the object again.

Any help is appreciated. Thanks,

Peter

Simple Route to an action in another controller

i have an MVC .Net C# project. have Plan Action under Home Controller. but i dont want to access this page as http://....../Home/Plans but i want to access it as http://....../Plans but i dont want to create Plans Controller. so i dont want to do a redirectToAction.

i am trying to use the Route Annonation as the following:

[Route("plans/")]
public ActionResult Plans()

[Route("plans/{actions}")]
public ActionResult Plans()

[Route("plans/index")]
public ActionResult Plans()

but none of the above worked for me. can you guys help me in this.

Populate DropDownList using AJAX MVC 4

I have a view in place that contains 2 @DropDownListFor's Helpers:

    @using (Html.BeginForm("CreateOneWayTrip", "Trips"))
    {
        @Html.ValidationSummary(false);
        <fieldset>
            <legend>Enter Your Trip Details</legend>

            <label>Start Point</label>
            @Html.DropDownListFor(m => m.StartPointProvince, (SelectList)ViewBag.Provinces, new { @Id = "province_dll", @class = "form-control" })
            @Html.DropDownListFor(m => m.StartPointCity, (SelectList)ViewBag.Cities, new { @Id = "city_dll", @class = "form-control" })

            <p style="float: none; text-align: center;">
                <button type="submit" value="Create" class="btn btn-info btn-circle btn-lg">
                    <i class="fa fa-check"></i>
                </button>

                <button type="submit" value="Create" class="btn btn-warning btn-circle btn-lg">
                    <i class="fa fa-times"></i>
                </button>
            </p>
        </fieldset>
    }

Here is the temporary model I use to Capture data:

 public class CaptureCreateTrip
 {
    [Required]
    [Display(Name = "Trip ID")]
    public string TripID { get; set; }

    [Required]
    public string StartPointProvince { get; set; }

    [Required]
    public string StartPointCity { get; set; }
}

One of the DropsDownList's are populated when the page is created and the second will be populated based on the option that the user chooses in the first DropDownList. To achieve this, i am using ajax. The javascript to I use looks like this:

$("#province_dll").change(function () {
        $.ajax({
            url: 'getCities/Trips',
            type: 'post',
            data: {
                provinceId: $("#province_dll").val()
            }
        }).done(function (response) {
            $("cities_dll").html(response);
        });
    });

Here is the Controller the AJAX calls:

  [HttpPost]
  public ActionResult getCicites(int provinceId)
  {
      var lstCities = new SelectList(new[] { "City1", "City2", "City3" });

      return Content(String.Join("", lstCities));
  }

Up until this point everything works - When I choose a value in my Province DropDown the javascript event fires and the Controller action does return the select list values to the Cities DropDown, the problem however is that the data(of the formatof the data) that the Action returns is incorrect. I Tested this by creating a Paragraph element and updating it's text with the return value of the ajax call, which is : "System.Web.Mvc.SelectListItemSystem.Web.Mvc.SelectListItemSystem.Web.Mvc.Select‌​‌​ListItem"

*Note: I am new to ajax and in the process of learning Jquery and AJAX.

ASP.NET MVC: Unauthenticated User Always Redirected to Login page

I've been trying to fix this for a week now, I tried everything that crossed my mind. I am creating web app using asp.net mvc 4 template. Problem is that I am always redirected to login page before I can't access any route without log in first. Not even register new user, which is absurd. I'm using simple membership and default Account controller and I even tried removing [Authorize] attribute from Account controller, but even then I'm redirected to login page. My Account controller looks like this:

[Authorize]
[InitializeSimpleMembership]
public class AccountController : Controller
{
...
    [AllowAnonymous]
    public ActionResult Register()
    {
        return View();
    }

My web config is:

    <authentication mode="Forms">
      <forms loginUrl="~/Account/Login" timeout="2880" />
   </authentication>

In chrome when I click on Register link, I get this error enter image description here

center image in thumbnail

This is what I have (the images inside an anchor):
enter image description here
And I want that low res images will be centered like this: (edited with paint)
enter image description here

This is the razor view:

<div>
<div class="row">
    @foreach (var item in Model)
    {
        <div class="col-md-3 ">
            <div class="thumbnail centerThumb" style="height:345px; width:280px;margin-bottom:15px">
                <div style="height:125px; ">
                    <a href="@Url.Action("Details", "Items", new { id = item.ItemID})">
                        <img src="~/Content/thumbnails/@item.Img" alt="thmbnail" width="255" class="img-rounded centerThumb">
                    </a>
                </div>
                <div class="caption">
                    <h3>@Html.DisplayFor(modelItem => item.Name)</h3>
                    <p style="height:95px">@Html.DisplayFor(modelItem => item.Description)</p>
                    <p style="position:fixed">
                        <a href="#" class="btn btn-primary" role="button">Add to Cart</a>
                    </p>
                    <p style="margin-left:50%"> @Html.DisplayFor(modelItem => item.Price) </p>
                </div>
            </div>
        </div>
    }
</div>

AngularJs (client side) with ASP.NET MVC 5 (server side)

I would like to learn AngularJs. I'm familar with ASP.NET MVC. I'm going to write some web app and I want to use AngularJs in client side and ASP.NET MVC 5 in server side.

I project solution:

  • Project Web - client side ( AngularJs)
  • Core (DAL, repositories, business layer) (C#)
  • Test

Is is good architecture ? What do you think about it ?

MVC with Quartz Service - Not working

I have successfully implemented Quartz as embedded and service. Everything works fine except one. MVC with embedded Quartz works fine but not with service.

I placed MVC project's dll into Quartz folder as instructed and run MVC project and through MVC project i accessed Quartz service and assign job. Quartz successfully puts entry into database(I have used AdoJobStorage) but still job is not triggered by Quartz service.

I have checked things like is service running and beside if i have console application it works fine.