I'm using mvc structure model like http://stackoverflow.com/a/5863936

class User extends Model {
   public function CheckUsername($username) {
       // ...
       $sql = "SELECT Username FROM" . $this->usersTableName . " WHERE ...";
       return $this->_db->ExecuteObject($sql, $data);
   }
}

$model->CheckUsername('foo');

my folder structure is like:

model/
/user_model.php   
/read_model.php  
/..._model.php    

each file is match a table name..

I have question, I found I use each model file just do similar thing crud so if I change it to only one model.php and function something like

public function select_where_1_column($table, $column_1) {
   $sql = "SELECT * FROM $table WHERE $column_1 = :$column_1";
}

public function select_where_2_column($table, $column_1, $column_2) {
   $sql = "SELECT * FROM $table WHERE $column_1 = :$column_1 AND $column_2 = :$column_2";
}

public function insert($table, $data) {
 count $data array and insert ...
}

is this a bad idea? most people how to do? like above original code(have each model file..) ? any suggestion will be appreciate!!

I was developing asp.net MVC with DevExpress in Razor View. I need to make client side events so i try to access my control by control name. But i cannot. Pleae help me.

Below mycode.

//_Layout.cshtml

<!DOCTYPE html>

<html>
<head>

@Html.DevExpress().GetStyleSheets(...)
@Html.DevExpress().GetScripts(...)

<script type="text/javascript">

//When i click the button, i wanna change button text.
//But i cannot find 'btnTest'

    function testFunc() {
        btnTest
    }

</script>
</head>

<body>
    @Html.DevExpress().Button(settings =>
{
    settings.Name = "btnTest";
    settings.UseSubmitBehavior = true;
    settings.EnableClientSideAPI = true;
    settings.Text = "ABC";
}).GetHtml()
@RenderBody()
</body>
</html>

Consider the following ASP.NET MVC razor view snippet which defines a helper

@helper FieldFor<TModel>(Expression<Func<TModel, string>> expression)
{
    <div class="form-group">
        @Html.LabelFor(expression,
                       htmlAttributes:
                           new {@class = "control-label col-md-2"})

        <div class="col-md-10">
            @Html.EditorFor(expression,
                            new
                            {
                                htmlAttributes =
                                new {@class = "form-control"}
                            })
            @Html.ValidationMessageFor(expression, "",
                                       new {@class = "text-danger"})

        </div>
    </div>
}

What is the pattern to convert it to a method of a class similiar to:

public static MvcHtmlString FieldFor(this HtmlHelper helper, FieldFor<TModel>(Expression<Func<TModel, string>> expression))
{
   /* Method */
}

All the examples I have found focus on generating markup which doesn't rely on other HTML helpers.

I was developing asp.net MVC with DevExpress in Razor View. I need to make client side events so i try to access my control by control name. But i cannot. Pleae help me.

Below mycode.

//_Layout.cshtml

<!DOCTYPE html>

<html>
<head>

@Html.DevExpress().GetStyleSheets(...)
@Html.DevExpress().GetScripts(...)

<script type="text/javascript">

//When i click the button, i wanna change button text.
//But i cannot find 'btnTest'

    function testFunc() {
        btnTest
    }

</script>
</head>

<body>
    @Html.DevExpress().Button(settings =>
{
    settings.Name = "btnTest";
    settings.UseSubmitBehavior = true;
    settings.EnableClientSideAPI = true;
    settings.Text = "ABC";
}).GetHtml()
@RenderBody()
</body>
</html>

hello everyone

i have a project where am using ASP.NET Identity 2.0. in this project am following the Onion architecture. the layers are :

1.UI: no reference to Owin or ASP.Net Identity

2.AuthenticationService:contains a wrapper for the asp.net identity usermanager.this wrapper implement an interface that lives in the Bal layer.this layer also contain my custom UserStore.

3.Dal: DbContext lives here.

4.Bal: contain Domaine entities and interfaces .no reference to Owin or ASP.NET identity or anything else.

5.DependencyResolver: Owin Startup is here plus some Ninject Modules and the NinjectWebCommon.So am Using Ninject.

till now everything is fine. users are happy creating accounts and ,they can login/logout/manage any time they want.the problem am facing now is with the Authorize(Role="rolename").it just doesn't work.

[Authorize(Users="pedro")]
[Authorize]

both of these works

[Authorize(Roles="Admin")]

this is one no.

in my Database i have users who belongs to the Role Admin.I am not sure why this doesn't work.mybe because i moved all the authentication stuff to another layer so the IPrincipal.IsInRole(string role) can't figure out how to check this anymore.

am working on creating a custom Authorize attribute or create some extensions. but i decided to seek your advices first.

Thank you for your time

I have problem in MVC . I Controller that have 2 method , thease 2 method return value from web service . if my value be null or i have exception in my try cath . let me i explain on code .

             var cheq = new List<ChequeDTO>();
            var cust = new CustomerDTO();
            cheq = Service.Cheque.Instance.GetRejectedChequeInq(1, nationalcode, "", "", "").ReturnValue.ChequeItem.ToList();
            cust = Service.Cheque.Instance.GetRejectedChequeInq(1, nationalcode, "", "", "").ReturnValue;

            var cheqdto = new PageData<ChequeDTO>();
            cheqdto.Data = cheq;
            cheqdto.Total = cheq.Count;
            var id = new IdentifingInfo();
            id.Name = cust.Name;
            id.RegisterPlace = cust.CDSbt;
            id.NationalCode = cust.IDNO;
            id.RegisterDate = cust.DTSbt;
            id.RegisterNumber = cust.NOSbt;
            id.RegisterPlace = cust.CDSbt;


           var  cheqItem = new List<ChequeItemVM>();
            if (cheqdto.Data == null)
            {
                return Content("موردی یافت نشد");
            }
            else
            {
                foreach (var i in cheq)
                {
                    var cheqItems = new ChequeItemVM
                    {
                        AccountNumber = i.ACCNTNO,
                        Ammount = i.AMCHQ,
                        BankId = i.CDBNK,
                        Branch = i.CDSHB,
                        BranchName = i.DESC,
                        ChequeDate = i.DTCHQ,
                        ChequeID = i.IDCHQ,
                        ChequeNumber = i.NOCHQ,
                        CurrencyAmount = i.CONVRATE,
                        CurrencyCode = i.CDARZ,
                        RejectDate = i.BCKDTCHQ
                    };

                    cheqItem.Add(cheqItems);
                }
                cheqdto.Sum = cheqItem.Sum(s => s.Ammount);

                RejectedCheque.BLL.InsertBLL.Instance.Insert(cheqItem, id.Name, id.RegisterDate, id.RegisterNumber, id.NationalCode, 1, "", "", "", branch, userID, ip, id.RegisterPlace);
                return Json(new { cheqdto.Data, cheqdto.Total, id.Name, id.NationalCode, id.RegisterDate, id.RegisterNumber, id.RegisterPlace ,cheqdto.Sum});

cheq and cust are two value that one of the it return list and the other one it return one value. how can i handdle the null value . i also use kendo ui to bind data in grid. and this is my kendo ui script

          GetActualRejectedCheque: new kendo.data.DataSource({
        transport: {

            read: {
                dataType: "json",
                type: 'Post',
                url: arg.ActualCustomerUrl,
                data:
                    {

                        NationalCode: function () { return vm.Nationalcode },
                    }
            }
        },
        error: function (e) {
            debugger;
            showAlert('  در برنامه خطایی رخ داده است  <br/>' + "<spna style='color:red'>" + '</span>', null, 'هشدار');

        },
        schema: {
            parse: function (data) {
                debugger;
                var total = kendo.toString(data.Total,'n0');
                var Name = kendo.toString(data.Name, 'n0');
                var registernumber = kendo.toString(data.RegisterNumber, 'n0');
                var RegisterPlace = kendo.toString(data.RegisterPlace, 'n0');
                var NationalCode = kendo.toString(data.NationalCode, 'n0');
                var RegisterDate = kendo.toString(data.RegisterDate, 'n0');
                var sum = kendo.toString(data.Sum, "n0");



                vm.set('total', total);
                vm.set('name',  Name);
                vm.set('RegisterNumber', registernumber);
                vm.set('RegisterPlace', RegisterPlace);
                vm.set('NationalCode', NationalCode);
                vm.set('RegisterDate', RegisterDate);
                vm.set('sum', kendo.format('{0} {1} {2}', '', sum, 'ریال'));


                return data;
            },
    total: "Total",
    data: "Data"
},

MVC Noob here.

Basically, I'm trying to call a function that's in an apicontroller. Here's the apicontroller side:

[HttpPost]
    public HttpResponseMessage<String> Recognize(string strokes)
    {
        var strokePointsData = JsonConvert.DeserializeObject<dynamic>(strokes);

        var strokeCollection = GetStrokeCollectionFromPoints(strokePointsData);

        var inkAnalyzer = new InkAnalyzer();

        inkAnalyzer.AddStrokes(strokeCollection);

        var analysisStatus = inkAnalyzer.Analyze();

        if (analysisStatus.Successful)
        {
            var recognizedString = inkAnalyzer.GetRecognizedString();
            return new HttpResponseMessage<string>(recognizedString);
        }
        else
            return new HttpResponseMessage<string>("Data not recognized");
    }

And here's the JS:

$('#submitBtn').click(function () {
        $.post('/api/Recognition/Recognize',
               { strokes: JSON.stringify(strokesHistory)},
               function (result) {
                   alert(result);
               });
    });

Yet every time I compile and run, I get a "Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://localhost:1409/api/recognition/recognize" error message. This tells me that it's looking for an object in the root folder in /api/recognition/recognize, but I don't see any folders like that in the root folder, so this error makes sense. Yet, from all the research I've done, it looks like the URI I have above should be the right context. What am I missing?

i want to redirect from on page to another on mvc and pass some parameter and get them on second page.

my parameter is something like this

?id=UXodaA54Iqo+gId3avkIqA

but when i get this parameter on the second the page some characters like "+" removed and the parameter has been changed to this

    UXodaA54Iqo gId3avkIqA

my action is

    [ValidateInput(false)] 
    public ActionResult test(string id)
    {
        return view();
     }

what is the best way to handle it just for this action because i do not want to put some thing like this on my web config

  <httpRuntime requestValidationMode="2.0" />

In a regular AbstractActionController, you can use the forward controller plugin to forward the request to another controller under specification of that controller's name and some parameters, like

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        $other_result = $this->forward()->dispatch('Application\Controller\Other', ['action' => 'doit']);
        return [
            'indexdata' => 'test',
            'otherdata' => $other_result
        ];
    }
}

I have implemented a restful API for the entities in our project using the AbstractRestfulController, and I figured I could just call the corresponding action on that controller i. e. when I want to update one of my models. That way I would not have to rewrite the CRUD logic a second time.

But is forwarding to an AbstracRestfulController even possible? Passing an action parameter to the dispatch method doesn't seem to be the solution, because the restful controller checks the request method (GET, POST, PUT etc.) to map the request to one of its restful methods (get(), getList(), update() or create()) instead of an action parameter. Of course one could just send an HTTP request to 'localhost' to invoke the restful controller, but that doesn't feel very elegant.

Another possibility I could think of to centralize the CRUD logic was creating a special service which will then be used in the restful controller and everywhere else I need to alter an entity. Is this the way to go? Or did I just miss how to forward to an AbstractRestfulController?

As shown below, I have a dummy memory store which returns a complex object. I would like to bind this complex object to the form. Because it's a complex object, I am binding the object through two MVC groups. The problem happens when the model is refreshed (through the "Fetch" button). The outer MVC group is refreshed, but the inner one is not. It works only if I manually re-set the target property of the inner MVC group:

dijit.byId('sub-group').set('target', model.prop7);

Is there any other, better way to do this?

<script type="text/javascript">
    // Create dummy store
    var store;
    require(['dojo/store/Memory'], function(Memory) {
        store = new Memory({
            data: [{
                id: 1,
                prop1: 'prop 1 value',
                prop2: 'WA',
                prop7: {
                    prop8: 'prop 4 value',
                    prop9: 'prop 5 value'
                }
            }]
        });
    });

    // Create model for MVC
    var model;
    require([
        'dojo/dom',
        "dojo/parser",
        "dojo/Stateful",
        "dojo/domReady!"
    ], function (dom, parser, Stateful) {
        model = new Stateful();
    });

</script>

<button data-dojo-type="dijit/form/Button" data-dojo-props="iconClass: 'dijitIconDatabase'">
    <script type="dojo/on" data-dojo-event="click">
        var data = store.get(1);

        model.set(data);

        //dijit.byId('sub-group').set('target', model.prop7);
    </script>

    Fetch
</button>


<form data-dojo-type="dijit/form/Form" id="form" data-dojo-type="dojox/mvc/Group" data-dojo-props="target: model">
    <script type="dojo/require">at: "dojox/mvc/at"</script>

    <div class="row">
        <label for="text">Text:</label>
        <input id="text" data-dojo-type="dijit/form/ValidationTextBox" required="true" data-dojo-props="value: at('rel:', 'prop1')"/>
    </div>

    <div class="row" id="sub-group" data-dojo-type="dojox/mvc/Group" data-dojo-props="target: model.prop7">
        <label for="text2">Text 2:</label>
        <input id="text2" data-dojo-type="dijit/form/ValidationTextBox" required="true" data-dojo-props="value: at('rel:', 'prop8')"/>
    </div>
</form>

I am working on MVC 3.0 application where I want to secure my URL like http://myapplication/Project/edit/12 so any one can change this ID. So I wan to secure (encrypt) this URL.

and my application very large near about 40-50 pages so add encryption and decryption logic in each view and controller's each action that is not a good idea.

So I want to add some thing in my global.aspx.cs, so how can I achive this?

you answer will be really appreciable.

hi every one i wrote this class

class member {



public $cf;

public $text;



public function __construct() {

    $this->cf = new cfg();

    require_once 'theme/v1/login.php';

}



public function login($username, $password) {

    $salt = $this->getSalt($username);

    if ($salt != null) {

        $password = md5(md5($password) . $salt);

        $exe = $this->cf->prepare('SELECT * FROM `user` WHERE `username`=:username AND password=:password');

        $exe->bindParam(':username', $username, PDO::PARAM_STR);

        $exe->bindParam(':password', $password, PDO::PARAM_STR);

        $exe->execute();



        if ($exe->rowCount() == 1)

            $this->text = 'yes';

        else {

            echo 'no';

        }

    } else {

        echo 'user not found';

    }

}



private function getSalt($username) {

    $exe = $this->cf->prepare('SELECT * FROM `user` WHERE `username`=:username ');

    $exe->bindParam(':username', $username, PDO::PARAM_STR);

    $exe->execute();

    if ($exe->rowCount() != null) {

        $salt = $exe->fetchAll();

        return $salt[0]['salt'];

    }

}

}

and want to get variables values in view when try to access to them with

$this->text

returned null and variable not changed in methods how can i access to changed version of variables .

I have the following scenario : I have one big page which contains several tabs, say TabA,.tabB, tabC. The user can submit the form if only he fills all the mandatory fields of the tabs. Now there are some dependencies between the select box elements of these tabs. Like selectbox1's selection determine the list of options for select2, similarly between select 2 and 3. I know the list can be easily fetched via ajax. But another complexity is that after fillin data for tab 2 I have the option for Add More. Which results into the duplication of the entire tab. I did this with jquery clone, but it does not populate the list of selec box.also how do I maintain the count of no of tabs added as user can also remove. And for dynamically created div how the dependencies will be resolved? please tell a suitable approach for this.

Hi I have a umbraco site setup at the moment. It is the latest version of umbraco.

Umbraco does not support mvc 5 as of yet. I am trying to setup an admin area for the site. I want the admin area to use the default setting you get with a new mvc site as in Microsoft.AspNet.Identity.

Alot of the class that Microsoft.AspNet.Identity dont seem to work well within the umbraco site. I.e. I have assembly that are reliant on different versions of assembly that are already in the umbraco solution.

I looked at creating a virtual application for another mvc site within the umbraco site. This was failing based on

Could not load file or assembly 'umbraco' or one of its dependencies. When this reference is added other errors occur.

I am best trying to add the functunality login area in the umbraco.web.ui solution itself, a virtual application directory with a new mvc site or another approach. Any help would be most appreciated.

Is it possible, reliable and secure to cache all entities in distrubuted cache and notifies dao layer on update? My possible idea is;

  • Use JPA 2.1 and Hibernate implementation.
  • On creation persist it db
  • After persisting it, cache it to distrubuted cache.
  • Canalise all read actions to cache
  • on update notify dao layer to update entity .

I've been scratching my head and reading tons of posts but couldn't figure this out.

I have a Person table (see following). Entities in that table can have Children and Parents, who also are in the same table.

public class Person
{
    public int ID { get; set; }
    public int Name { get; set; }
    public virtual ICollection<Person> Children { get; set; }
    public virtual ICollection<Person> Parents { get; set; }
}

My model builder in DataContext is like this :

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>()
            .HasMany(c => c.Children)
            .WithMany(p => p.Parents)
            .Map(m=>
                {
                    m.ToTable("ParentChild");
                    m.MapLeftKey("ParentID");
                    m.MapRightKey("ChildID");
                });
    }

This works fine and automatically creates a table named ParentChild with ParentID and ChildID.

Now the thing is, I want to delete a Person who has children, but without deleting the children. So I guess I need to also delete the corresponding line in my ParentChild table (which is auto-generated), but don't know how to do that.

Note : I've also tried to explicitly create the ParentChild table, but this doesn't work, it's rejected when doing add-migration.

To give you more information, here is the error I get when I try to delete one of the row in Person :

The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.PersonPerson_dbo.Person_Person_ID". The conflict occurred in database "MyDatabase", table "dbo.ParentChild", column 'ParentID'.

(By the way, I don't know why it talks about a PersonPerson database since I give my auto-generated relation database the name ParentChild. But even if I don't give it a name, it doesn't work).

Last thing, here's the Remove() stub in PersonController (I left as it was originally made by Scaffolding) :

public ActionResult Delete(int id)
    {
        try
        {
            Person person= db.Persons.Find(id);
            db.Persons.Remove(patient);
            db.SaveChanges();
        }
        catch (RetryLimitExceededException dex)
        {
            return RedirectToAction("Delete", new { id = id, saveChangesError = true });
        }
        return RedirectToAction("Index");
    }

I hope someone can help me!

Thanks in advance for your help and cheers,

Marius

I'm getting a failure when trying to access data from a record out of a field that corresponds to a ManyToManyField.

models.py

class I(models.Model):
   t = models.CharField(max_length=255)
   p = models.ManyToManyField(P)

class P(models.Model):
    name = models.CharField(max_length=255)

forms.py

class MyForm(forms.Form):
   t = forms.CharField(required=True, widget=forms.TextInput())
   p = forms.ModelChoiceField(queryset=P.objects.all().order_by('name'),
                              widget=forms.SelectMultiple())
   # other_fields_requiring_custom_save = ...

def save(self):
    I = I.objects.create(
        t = self.data['t'],
        p = self.data['p'], 
    )
    I.save() # it breaks here: 'P' is an invalid keyword argument for this function" in ManyToManyField

It breaks on save when I try to set p = self.data['p']. In the debugger I can see:

data = <QueryDict: {u'p': [u'2', u'1'], u't': [u'aaa'], ... >

I started a MVC5 project with Individual User Accounts, I ran the initial migrations to get the database in place for users, roles et cetera.

I wrote a RolesController in an Admin Area, but from there, I am stuck. The first error was telling me to use roleManager, and include it in web.config. Alright, I did that according to an example I found on StackOverflow based on WebMatrix.WebData, but it didn't feel right, because it's a deprecated package on NuGet and integrated in Microsoft.AspNet.WebPages.WebData.

And there the trouble started, giving more and more errors, which I Googled and fixed by updating AspNet.WebPages.Data and other WebPages related packages.

Then, running the solution happened to give me more and more trouble, because eventually all solutions happened to be for MVC4/Membership instead of MVC5/Entity. I removed WebMatrix.WebData and kept WebPages at the new versions NuGet got me.

I then happened to stumble on a new word of advice found here. So I added that line to Web.Config, and everything ran happily ever after. Until I wanted to add a role, saving it took ages, resulting in this error: Unable to connect to SQL Server database. (System.Web.HttpException).

My ConnectionString never changed in Web.Config, so I am lost at what to do now. I hope someone can help me out. This is the connectionString: connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-ImpHer-20141111023559.mdf;Initial Catalog=aspnet-ImpHer-20141111023559;Integrated Security=True"

So I'm having an issue of updating my model. Right now I have a chart that is being generated when my page is visited through data provided by the model, above this chart is going to be a datapicker that allows the user to choose a data, upon choosing a new data I want the controller to update the information in the model, then refresh the chart to display the new data. Right now I have no idea how to update my model.

My model at the top of my page

@model StatisticsModel

this is the code for creating the chart. We're using the Kendo library for this

<div id="MessageCountDiv"> @(Html.Kendo().Chart(Model.vendDateModel) .Name("MessageCount") .ChartArea(background => background.Background("")) .Title("Message Count") .Legend(legend => legend.Visible(false)) .CategoryAxis(category => category.Categories(model => model.vendor)) .Series(series => series.Bar(model => model.count) .Labels(c => c.Visible(true).Template("#= kendo.format('{0:P}', percentage)#"))) .SeriesColors("red", "blue") .Tooltip(tooltip => tooltip.Template("${ category } - ${ value }").Visible(true)) .Tooltip(tooltip => tooltip.Color("white")) ) </div>

When the user changes the desired date, this function is called

function updateChart() { var stDate = $('#start').val(); var edDate = $('#end').val(); $.ajax({ url: 'updateChart', data: { startDate: stDate, endDate: edDate }, success: function () { $('#MessageCount').data("kendoChart").refresh(); } }); }

Right now this is the controller, it is currently using the StartDate and EndDate variables to a view in our database for information falling between those two dates.

public ActionResult updateChart(string startDate, string endDate) { globStartDate = startDate; globEndDate = endDate; using(SMSTestHarnessDBEntities _db = new SMSTestHarnessDBEntities()) { foreach (var a in _db.VendorDates1.SqlQuery("Select Vendor, CURRENT_TIMESTAMP AS DateSent, Counter FROM (Select DISTINCT Vendor, SUM(Counter) AS Counter FROM [VendorDates] WHERE DateSent BETWEEN @p0 AND @p1 GROUP BY Vendor) AS temp", globStartDate, globEndDate).ToList()) { model.vendDateModel.Add(new DateModel { vendor = a.Vendor, count = Convert.ToInt32(a.Counter) }); } } return View(model); }

So is there a way to change the model from the controller so that when I refresh my chart it will display the new data?

I have been searching about this error for a couple of weeks. And I couldn't find the right answer. So I am done about that. Here is my ASP.net c# code

    MySqlDataAdapter cmd = new MySqlDataAdapter("select  * from haberler  order by id desc  limit 10 where kategori='anaokulu'", con);

and the error is :

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where kategori='anaokulu'' at line 1

any help will be so helpful, just make me try something to solve this problem..

Thank you.

I am currently building an intranet site and on this site, we have websites people would frequently use.

There are a couple of websites where people need to login though. So I was wondering if there is a way to automatically fill in the username and password box on that website when the user clicks the link for it. The login info will never change and all users have to use the same login. Something that automates this process would make things easier for the user.

So in my aspx, I would have something like this (not this exact website but a different one):

<a href="https://go.litmos.com/account/Login" target="_blank">Litmos</a><br />

I'm not sure if I need to use the code behind to do what I want or maybe some Javascript.

The type of functionality I am looking for is like the one found in KeePass. Where you enter your username and password along with a website url and when you open that website from KeePass, it fills the login info for you. I realize that that is a desktop application and I'm building an ASP.NET website. I want to know if something like this is possible and if so, how.

Just so you know, I'm using C# for the code behind for the intranet site.