mardi 28 février 2017

C# MVC upload CSV file & import it to SQL server by creating table dynamically

I have a requirement where we need to import data from a .csv file to SQL server by creating the table dynamically. The reason for dynamic table creation is because the .csv file will have columns changing. We have to drop the existing table & recreate a new table based on the header information in the .csv file. (user may be running some diagnostic queries on that table later on)

I'm using C#.net MVC-3 & SQL Server 2014 standard version.Please let me know the best possible ways of achieving this.

Thank you.

How to set Max on input text using angular JS

I want to set max value for an amount field using angular JS

If i enter value > 10 i want to display an error message next to the textbox. Since type="text" it is not working like number.

<input type="text" name="input" ng-model="example.value"   ngmin="0" ngmax="10" >

dimanche 26 février 2017

Google Analytics - Universal Analytics tracking two environments

I am using Google's Universal Analytics in MVC application for Page visits tracking purpose. I have three environments(i.e, Dev , Test & UAT) to test my code and as a primary user I have access to all three environments.

After initial test the code has been moved to Test environment from Dev environment. And again the code has been moved to UAT environment. Now the code resides in all three environments.

In my google analytics website, I have given UAT environment URL(domain name) alone for tracking purpose but now the problem is, when I login into Test and UAT environments it tracks both. When I navigate to different page in Test environment it tracks my navigation page.

As I mentioned above, I have given UAT domain name in GA website. And I want to track UAT alone and not other environments.

Do I need to configure any settings in Google Anlytics website?

Any suggestion please. Thanks in advance.

vendredi 24 février 2017

Trigger for multiplication of one table vale into another table value

This will be displayed in a monospaced font. The first four spaces will be stripped off, but all other whitespace will be preserved.

Markdown and HTML are turned off in code blocks:
<i>This is not italic</i>, and [this is not a link](http://example.com)

To create not a block, but an inline code span, use backticks:

The $ character is just a shortcut for window.jQuery. If you want to have a preformatted block within a list, indent by eight spaces:

  1. This is normal text.
  2. So is this, but now follows a code block:

    Skip a line and indent eight spaces.
    That's four spaces for the list
    and four to trigger the code block.  I have two tables 
    
    

    FirstTable is

    Id || EB || EBC || DG || DGCost

    1 || 10 || Null || 10 || Null 1 || 5 || Null || 20 || Null 2 || 20 || Null || 10 || Null

    and Second Table Is

    Id || EbCost || DGCost

    1 || 2 || 3

    2 || 3 || 6

    and when i insert values in firsttable these (EbCost,DGCost)values multiply with secondtable (EB,DG) and the reult will be update in (EBC,DGC) columns corresponding with ID final output look like

    Id || EB || EBC || DG || DGC

    1 || 10 || (10*2)=20 || 10 || 30

    1 || 5 || 10 || 20 || 60

    2 || 20 || 60 || 10 || 30


    I need Query Urgently.. can any one help me here

jeudi 23 février 2017

Prevent javascript execution during page refresh

In MVC application CSHTML page, I have some set of JavaScripts which performs some calculation based on page hits but I do not want to perform calculation during page refresh.

How to ignore script execution during page refresh?

mercredi 22 février 2017

How to get FileStreamResult Output

I have a program I'm modifying that is basically a delivery schedule website using ASP.NET MVC3. The addition I'm giving the site is the ability to print a manifest (it can already print a delivery schedule) but I've run into a snag which would be my lack of understanding. Basically I have it setup so when a user pushes the button it makes a call to populate the manifest. All I need to do now is print it to PDF using FileStreamResult (there's a method already in place for this) I'm just not sure how to get the output from my PrintShippingManifest method to return something a FileStreamResult method can use.

I've tried googling and searching this site, but I'm now into information overload and could use some direction.

Here's the PrintShippingManinfest in the controller:

  public JsonResult PrintShippingManifest(int id)
        {
            var _manifest = new List<ShippingManifestRootJSON>();
            FillShippingManifest(_manifest, id);
            return Json(new { result = "success", message = "OK" });
        }
        [HttpPost]

And this method as well:

 private void FillShippingManifest(List<ShippingManifestRootJSON> manifest, int id) //added by Chad
        {
            using (var tx = dbSession.BeginTransaction())
            {
                try
                {
                    var shipItems = dbSession.CreateCriteria<ShippingItem>()
                                .Add(Restrictions.Eq("DeliveryTicket.Id", id))
                                .AddOrder(Order.Asc("DeliveryOrder"))
                                .List<ShippingItem>();

                    foreach (var _item in shipItems)
                    {
                        var _root = manifest.Find(x => x.JobNumber == _item.JobNumber);
                        if (_root == null)
                        {
                            _root = new ShippingManifestRootJSON() { JobNumber = _item.JobNumber, Name = _item.JobName, ID = _item.Id };
                            manifest.Add(_root);
                        }
                        var _manifestItem = Mapper.Map<ShippingManifestSectionJSON>(_item);

                        _root.Add(_manifestItem);
                    }

                    foreach (var _job in manifest)
                    {
                        foreach (var _section in _job.Sections)
                        {
                            FillSectionWithData(_section);
                        }
                    }

                }
                catch (Exception ex)
                {
                    if (tx != null)
                        tx.Rollback();


                }
            }
        }

mardi 21 février 2017

Dynamic vs strongly typed elements

I'm a web developer who is currently using mvc3 razor and Umbraco to create web applications. I've not been in this job long, and have moved over from using dynamic to strongly typed elements to follow standards.

Ive never really been given much of a reason, and searching online it seems clear that its much easier to follow and debug set type variables, but I'm confused about using it in functions.

For example, when using Umbraco Content, I've now switched to 1Umbraco.TypedContent1. Im guessing that it returns a strongly typed variable, but are there any other benefits to it other than debugging?

Unable to Post data to Asp.Net Web API hosted on Microsoft Azure

I have written an Asp.Net web api in which i wrote put, post,get and delete to perform crud in Sql azure database. Database and API are both live on Microsoft Azure. I am successfully able to call GET controller and fetch data in browser. When i try to post hard coded data to it via a console app, it does nothing (neither gives error nor exception). Below is the Web API controller:

public HttpResponseMessage Post([FromBody] Product prod)
    {
        try
        {
            se.Products.Add(prod);
            se.SaveChanges();

            var message = Request.CreateResponse(HttpStatusCode.Created, prod);
            message.Headers.Location = new Uri(Request.RequestUri + prod.Product_ID.ToString());
            return message;
        }
        catch (Exception ex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
        }
    }

Method from the client console app to send data is shown in this picture

I tried to inspect this method by putting a breakpoint at response.Response got nothing in it but showed a bad request. Here is the screenshot to it.

Kindly help me how to successfully post data to database via web api hosted on azure. Thanks :)

Soap web service through the error(SoapFault - faultcode: 'a:InternalServiceFault')

please help me to resolve the error.

public static HashMap<String, Object> callSOAPServer(StringBuffer soap /* YOUR XML GOES HERE*/,String action) {
    int count,size;
    int total=0;

    HashMap<String, Object> xMap = new HashMap<String, Object>();
    byte[] result = null;
    byte[] data = new byte[1024*1024];
    HttpClient httpclient = new DefaultHttpClient(); /* Your probably need to edit client for your needs, like timeout, scheme, etc */
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    DataInputStream is = null;
    boolean download = true;
   // HttpPost httppost = new HttpPost(/* YOUR URL GOES HERE */ );
    HttpPost httppost = new HttpPost("http://ift.tt/2m7ygcS");
    //httppost.setHeader("soapaction", action);
    httppost.setHeader("Content-Type", "text/xml; charset=utf-8");
    try {
        HttpEntity entity = new StringEntity(soap.toString(), HTTP.UTF_8);
        httppost.setEntity(entity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity r_entity = response.getEntity();
        if (r_entity != null) {
            result = new byte[(int) r_entity.getContentLength()];
            size = result.length;
            if (r_entity.isStreaming()) {
                is = new DataInputStream(r_entity.getContent());
                while((count = is.read(data, 0, data.length)) != -1) {
                    buffer.write(data, 0, count);
                    total +=count;
                }
            }
            buffer.flush();
            result = buffer.toByteArray();
            data = null;
            buffer = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        result = null;
    }
    if(result !=null){
        try {
            String sb;
            String sn;
            sb = new String(result, "UTF-8");
            sn = sb.replace("&amp;", "AMP"); //Precaution for SAX parser
            result = sn.getBytes();
            Log.d("",result.toString());
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        xMap.put("STATUS", "OK");
        xMap.put("SOAP", result);
    }else{
        if(xMap.get("STATUS") == null) {
            xMap.put("STATUS", "ERROR");
        }
    }
    httpclient.getConnectionManager().shutdown();
    return xMap;
    // List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    //nameValuePairs.add(new BasicNameValuePair("Username", "Hari"));
    //nameValuePairs.add(new BasicNameValuePair("Password", "Hh123456"));
    // nameValuePairs.add(new BasicNameValuePair("soap.toString()", HTTP.UTF_8));
    //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
}

Soap web service through the error(SoapFault - faultcode: 'a:InternalServiceFault')

dimanche 19 février 2017

Getting full request url - ASP.NET MVC

I have request to server like : "http://localhost/?asdhkjashdaskjdhqwehw".

And my Action :

public ActionResult Index()
{
     stringUrl = ;
     return RedirectToAction("Index","Home");
}

I want to get string : "asdhkjashdaskjdhqwehw" in Action Index.

vendredi 17 février 2017

MVC3 Partial view inside another partial view doesn't set model

I've got a partial view named "_Edit"
It is strongly typed, being "RegistryDTO" the model class

At a certain point, "_Edit" renders another strongly typed partial view named "_RelatedRequests", which's model class is simply String, using the following line:

@Html.Partial("_RelatedRequests", model.registryID);

Obviously, registryID is of type String
But for some reason, "_RelatedRequests"'s model is set to null, and any reference to "model" points to it's parent's model ("_Edit"), which obviously is a RegistryDTO object instead of a String one

What could be causing this?

mercredi 15 février 2017

MVC3 .net issue to show loading image when page loads

I'm pretty new to the MVC3 .net programming & recently in one of my internal projects I'm trying to implement a functinality where to display a loading image while the page is being loaded. (using jquery function calls.)

Issue: If i browse the default URL as we define in the route mapping. The image is not getting loaded but i can see all the styles getting populated on the page. But if i navigate to same page using the hyper link defined on the webpage the image is getting loaded as expected. I'm not sure what I'm missing here. It is same case for jquery load & jquery-ajax request/response functions (default navigation is not working while the hyperlink navigation is working).

Code:

            <style type="text/css">
            #loader {
            position: fixed;
            left: 0px;
            top: 0px;
            width: 100%;
            height: 100%;
            z-index: 9999;
            background: url('content/themes/base/images/preloader_8.gif') 50% 50% no-repeat rgb(249,249,249);
            opacity: .8;
        }
        </style>

        <script src="@Url.Content("~/Scripts/jquery.min.js")" type="text/javascript"></script>

            <script type="text/javascript">
                $(window).load(function () {
                    $("#loader").fadeOut("slow");
                });
                $(document).ready(function () {
                    $(document).ajaxStart(function () {
                        $("#loader").show();
                    }).ajaxStop(function () {
                        $("#loader").hide();
                    });
                });
        </script>      

And I have following tag defined in the body of index/home page,

<div id="loader"></div>

route mapping in my config file: (I don't think there is an issue here, because i can see the transparency style but not the defined image(preloader_8.gif).)

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}/", // URL with parameters
            new { controller = "Home", action = "Index"} // Parameter defaults
        );

    }

appSettings in Web.config and Web.Release.config

Trying to get simple <appSettings> for dev vs. prod.

My Web.config:

<appSettings>
  <add key="hello" value="debug" />
</appSettings>

My Web.Release.config:

<appSettings>
  <add key="hello" value="prod" />
</appSettings>

(both under <configuration>)

When I have it in Debug mode, and run my MVC site, I can do a simple return Content(WebConfigurationManager.AppSettings["hello"]); in my HomeController.Index and it returns dev. If I switch the mode to Release it still returns dev. I'd like to simulate prod mode without actually publishing to prod.

lundi 13 février 2017

To allow GET requests, set JsonRequestBehavior to AllowGet

i have bind bulk records in kendo ui grid.the response is return from Json .

I am getting Error while using below format:

Problem Code : Method 1: public JsonResult KendoserverSideDemo(int pageSize, int skip=10) {

            using (var s = new KendoEntities())
            {

                var total = s.Students.Count();

                if (total != null)
                {
                    var data = s.Students.OrderBy(x=>x.StudentID).Skip(skip).Take(pageSize).ToList();


                      return Json(new { total = total, data = data,JsonRequestBehavior.AllowGet });




                }

                else
                {

                    return null;
                }
            };

        }

Method2: Working fine using this:

public JsonResult KendoserverSideDemo(int pageSize, int skip=10) {

        using (var s = new KendoEntities())
        {

            var total = s.Students.Count();

            if (total != null)
            {
                var data = s.Students.OrderBy(x=>x.StudentID).Skip(skip).Take(pageSize).ToList();




                return Json(data, JsonRequestBehavior.AllowGet);
                }
            }

            else
            {

                return null;
            }
        };

    }

What is the problem in first Method 1:

"The model item passed into the dictionary is of type '" [duplicate]

i need show all category in view . i used this code for show all :

Category = Tabel name of Database

public List<Category> GetAllCategory()
    {
        return _repository.GetAll();
    }

/****************************************/

public ActionResult ListCategory()
    {
        return View(_CategoryService.GetAllCategory());
    }

/*****************************************/

i create model CategoryModel .

 public class CategoryModel 
{
    [Display(Name ="کد دسته")]
    public int CatID { get; set; }
    [Display(Name = " نام دسته")]
    public string CategoryName { get; set; }
    [Display(Name = " سر دسته")]
    public int ParentID { get; set; }
}

/**********************************/

and in view i use this :

@model IEnumerable<Amene.Models.CategoryModel>

but it show me this error :

The model item passed into the dictionary is of type 'System.Collections.Generic.List1[DA.Data.DB.Category]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[Amene.Models.CategoryModel]'.

o know i must user table name in view Category but i need use CategoryModel .

how can i do this ?

How to Sort Data's in DataTable?

I am currently working with a simple project on my own using asp.net mvc3 and bootstrap. I have this code below working perfectly. But my problem is in when displaying in my Data Table. As you can see in the code I order it by the PositionId and the Result in Controller is fine and but the problem is in data table.

ID's

Pres - 1

V. P - 2

Sec - 3

Code

public JsonResult LoadTableTest()
    {

        var Data = new List<object>();

        Data = (from a in db.testVotings
               orderby a.PositionID
                select new
                {
                    PosId = a.PositionID,
                    testID = a.testID,
                    Fullname = a.Fullname,
                    Position = a.Position,
                    party = a.party
                }).ToList<object>();

        return Json(new
        {
            data = Data
        }, JsonRequestBehavior.AllowGet);

    }

JS

var dataTablestest = $("#tbltest").DataTable({
    responsive: true,
    processing: true,
    info: true,
    search: true,
    stateSave: true,
    order: [[1, "asc"]],// [2, "asc"]],
    lengthMenu: [[50, 100, 200, -1], [50, 100, 200, "All"]],
    ajax: { "url": "/Voting/LoadTableTest" },
    columns:
    [
    { data: "PosId", title: "", orderable: true ,visible: false, searchable: false },
         { data: "testID", title: "",orderable: false, visible: false, searchable: false },
        { data: "Fullname", title: "FullName",orderable: false, sClass: "alignRight" },
        { data: "Position", title: "Position",orderable: false, sClass: "alignRight" },
        { data: "party", title: "Party",orderable: false, sClass: "alignRight" },
        { data: "ActionMenu", title: "Click to vote", searchable: false, orderable: false, sClass: "alignCenter",
            "mRender": function (data) {
                return '<center><label><input class="checkId" type="checkbox" /></label></center>';
            }
        }
    ]
});

HTML

 < table class="table table-striped table-bordered table-hover table-responsive nowrap" role="grid" style="width: 100%;" id="tbltest">
 < /table>

enter image description here enter image description here

dimanche 12 février 2017

I am getting "Server cannot set status after HTTP headers have been sent issue" in my live website

I have used MVC 3.0 with Orchard solution to develope this site.following is the details that i found in LOG file...

Exception information:

Exception type: HttpException 

Exception message: Server cannot set status after HTTP headers have been sent.

at System.Web.HttpResponse.set_StatusCode(Int32 value)

at System.Web.HttpResponseWrapper.set_StatusCode(Int32 value)

at System.Web.Mvc.HandleErrorAttribute.OnException(ExceptionContext filterContext)

at System.Web.Mvc.ControllerActionInvoker.InvokeExceptionFilters(ControllerContext controllerContext, IList`1 filters, Exception exception)

at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)

at System.Web.Mvc.Controller.<>c__DisplayClass1d.b__19()

at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1. b__0()

at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.b__7(IAsyncResult _)

at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()

at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)

at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.b__3(IAsyncResult ar)

at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()

at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)

at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)

at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.b__3(IAsyncResult asyncResult)

at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.b__3(IAsyncResult ar)

at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()

at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)

at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)

at Orchard.Mvc.Routes.ShellRoute.HttpAsyncHandler.EndProcessRequest(IAsyncResult result)

at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()

at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

samedi 11 février 2017

how to add textbox for modal with one to many relationship

i have two models "user" (id,username,address) and "sales" (id,descriprion,userid)

user can have multiple sales (one to many relationship)

and i want to add user information from mvc razor form and i also want to send sales information to controller from my form.

my question is what is the best way to do this task

I am using grid and a small form to add sales in a grid and want to post that grid with user information. i dont know how to do this.

please suggest me the best way to do this task. or the way that i am using how to post sales also with user information.

Here is the way i want to post this form

Click Image to see

jeudi 9 février 2017

how to get approximate values in textarea when I click on an item in the dropdown list items in mvc

how to get approximate data automatically in textarea when I click on an item in the dropdown list items in mvc in the edit action method

model

public partial class Service
{
    public int Id { get; set; }
    public string ItemName { get; set; }
    public string Description { get; set; }
}

view

    <div class="form-group">
        @Html.LabelFor(model => model.ItemName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10"><p>
            @Html.DropDownListFor(model => model.ItemName, new SelectList(new[] { "Core Banking", "ATM", "RTGS/NEFT", "IFSC Code", "Money Transfer", "Locker Facility", "Mobile Banking (MAMBA)" }), "Select")
            @Html.ValidationMessageFor(model => model.ItemName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.TextAreaFor(model => model.Description, 8, 100, null)
            @Html.ValidationMessageFor(model => model.Description, "", new { @class = "text-danger" })
        </div>
    </div>

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

}

controller

    public async Task<ActionResult> Edit(int? id)
    {
        if (id == null)
        {
            return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
        }
        Service service = await db.Services.FindAsync(id);
        if (service == null)
        {
            return HttpNotFound();
        }
        return View(service);

    }

    // POST: Services/Edit/5
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://ift.tt/1eddaz0.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Edit([Bind(Include = "Id,ItemName,Description")] Service service)
    {
        if (ModelState.IsValid)
        {
            db.Entry(service).State = EntityState.Modified;
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }
        return View(service);
    }

This is my controller, model, and view page here in the view page when I select an Item from the dropdown list, the corresponding data for the selected item should appear in the textarea just below the drop down list. But this cannot be done for me, Is this possible to do like that? Should I need to change my edit action method? How can I solve my problem ??

mercredi 8 février 2017

what is the maximum size of JsonResult in mvc Controller

I have to work on the MVC with angular based application, I have to retrieve 20000 thousand data from a database to send with Angular.

If I send below of 13000 data return from json, its returning error. else getting this error.

So have used the below solution, it works fine, But why have to use this , what is the limited size of JSON result.

  var jsonResult = Json(x, JsonRequestBehavior.AllowGet);

                    jsonResult.MaxJsonLength = int.MaxValue;
                    return jsonResult;

what is the maximum size of JsonResult it is in data size ?

enter image description here

Is it possible to access data from different data providers using Entity Framework db first approach in asp.net web application

I implemented this link: http://ift.tt/2klgi5C but I want this to be implemented using Database first approach any help.

Tree structure Link name in MVC-use List

I create tree structure using List but tree structure is generated but not found any property to give name to link or branch . Please suggest all suitable property and method of List class object. I found on net but I do not get any satisfy answers.

mardi 7 février 2017

How to send string id to controller using actionlink

i am tring to have links link this /View/test it is working only if it is int like /View/1

my view action link

   @Html.ActionLink(item.className, "View", "subject", new {id =item.className  },null)

my control action

       public ViewResult View(string id)
    {
        //some database
        return View();
    }

i get this error Server Error in '/' Application. if i change the id into anything it works fine but the link will looks like this : View?anything=par

disable an account with the ASP.NET Membership Provider?

MembershipUser user = Membership.GetUser("Yourusername");

if(user!=null){ user.IsApproved=false;

Membership.UpdateUser(user); }

This code is not working.Found error in last line as "this method is not specified in your file"

dimanche 5 février 2017

Get All Pdf Files from My Computer Folder

I want to get all the pdf files from my MyComputer Folder. I have written the code which is getting all of my drives successfully but there is an exception occuring and none of file is accessible. Here is the exception message. Please help me for this.

"Access to the path 'C:\$RECYCLE.BIN\S-1-5-18' is denied."

My requirement is to get all the pdf files and their paths from My Computer folder.

Thank you

How to fix order by?

I got this code in asp.net mvc3 controller for view and order in a dropdown. But my problem is as you can see in the picture below it order by text and next to it the number. How to fix this issue?.

ViewBag.AddrBarangay = new SelectList(db.Barangays, "BarangayId", "BarangayName", "").OrderBy(m => m.Text);

enter image description here

My dropdown selected value is not being posted to the controller in C# mvc

I am new to C# mvc. I have a simple form containing a dropdown list whose values are being populated from a ViewBag

@using (Html.BeginForm("GetSliderValues", "Slider",FormMethod.Post))
    {
   @Html.DropDownList("dvalue",(IEnumerable<SelectListItem>)ViewBag.names)

        <input type="submit" name="submit" value="Submit" />
    }

After submitting the form I am trying to get the selected value in the Controller as

[HttpPost]
    public ActionResult GetSliderValues()
    {
        ProviderName p = new ProviderName();
        p.Name = Request.Form["dvalue"];
        return View(p);

    }

But I am not receiving any value. p.Name is always being set to null.

vendredi 3 février 2017

mvc app design and GUIquestion

greeting mvc gurus...How would you construct your app to work the following way. I am using a database first setup and I am using the wizard to build my view.

The wizard built an index view that I like the layout of and currently this screen will be use by the user to see their line items.

But it would save bunches of time If I could also use this screen as an Admin screen where the User Admin could click an approve button that would run code behind that ran a microsoft sql server stored procedure or something.

Vs me having to build a new controller and views... Or do you have to build all that stuff new? Which is the easiest way even if its not the best way.

My Example is below The first view in the normal mode index view where the user sees their line item... enter image description here

This is what I would like to do using the same form that already exist. enter image description here

Or the best thing to do is to build a new set of controller and screens Many thanks guys!

jeudi 2 février 2017

Why i am not getting data from table [duplicate]

model

public class NewsList
{
    public int Id { get; set; }
    public List<ClsNews> NewsLst { get; set; }
}
public class ClsNews
{
    public int Id { get; set; }
    public string Description { get; set; }
}
public partial class News
{
    public int Id { get; set; }
    public Nullable<System.DateTime> Date { get; set; }
    public string Description { get; set; }
    public Nullable<bool> IsActive { get; set; }
}

view

<table class="table">
    @{int i = 1;}
    @for (var j = 0; j < Model.NewsLst.Count; j++)
    {
        <tr> 
            <td>
                @Html.HiddenFor(m => Model.NewsLst[j].Id)
                @Html.HiddenFor(m => Model.NewsLst[j].Description)
                @Html.DisplayFor(m => Model.NewsLst[j].Description.Substring(0,20))
                @Html.ActionLink("Read More", "NewsInnerPage", "News")
            </td>
        </tr>
        i++;
    }

controller

public ActionResult News()
{
    var res = db.News
     .Select(t => new ClsNews
     {
         Description = t.Description
     }).ToList();
    return View(res);
}

It seems to occur an error

"The model item passed into the dictionary is of type 'System.Collections.Generic.List'1[A.Models.ClsNews]' but this dictionary requires a model item of type 'A.Models.NewsList'"

I need to get the data in the description column to get to the view page. but that occurs an error. How can I resolve my problem?

ASP.NET MVC how to show DropDownList

I am trying to add Items into DropDownList without database. But output only shows "Testing..."

My Model class.

    public class DropDownListData
    {
        public DropDownListData()
        {
            City = new List<SelectListItem> { };
        }

        public List<SelectListItem> City;
    }

Controller

           public ActionResult Travel()
           {
               DropDownListData ddld = new DropDownListData();

               ddld.City = new List<SelectListItem>
               {
                   new SelectListItem {Value = "Paris" ,Text = "Paris"},
                   new SelectListItem {Value = "Moscow",Text = "Moscow"},
                   new SelectListItem {Value = "Yerevan" ,Text = "Yerevan" }
               };

               return View(ddld);
           }

View

@model ASP.NET.Test.Models.DropDownListData

@{
    Layout = null;
}

Testing...
@{
    Html.DropDownList("series", Model.City, "Choose City");
}

Why I don't see DropDownList. What am I doing wrong?

mercredi 1 février 2017

How to implictly convert from one datatype in a class to another in asp.net mvc?

How to implicitly convert from one datatype in a class to another in asp.net mvc. How can I change my error in the controller?

models

public class ClsNews
{
    public int Id { get; set; }
    public string Description { get; set; }
}
public class NewsList
{
    public int Id { get; set; }
    public string description { get; set; }
    public List<News> NewsLst { get; set; }
}
public partial class News
{
    public int Id { get; set; }
    public Nullable<System.DateTime> Date { get; set; }
    public string Description { get; set; }
    public Nullable<bool> IsActive { get; set; }
}

view

<table class="table">
    @{int i = 1;}
    @for (var j = 0; j < Model.NewsLst.Count; j++)
    {
        <tr>

            <td>
                @Html.HiddenFor(m => Model.NewsLst[j].Id)
                @Html.HiddenFor(m => Model.NewsLst[j].Description)
                @Html.DisplayFor(m => Model.NewsLst[j].Description.Substring(0,20))
                @Html.ActionLink("Read More", "NewsInnerPage", "News")

            </td>
        </tr>
        i++;
    }
</table>

this is my Controller

News news = await db.News.FindAsync(id);
NewsList nl = new NewsList();
nl.Id = id;

nl.description = (db.News.Where(h => h.Id == id)).Count() > 0 ?
                    (db.News.Where(h => h.Id == id)).First().Description : string.Empty;

var res = db.News.Where(s => s.Id == id).Select(t => new ClsNews 
{
    Id = t.Id,
    Description = t.Description
}).ToList();
nl.NewsLst = res;
if (news == null)
{
    return HttpNotFound();
}
return View(nl);

The error is generating in the controller where the value in variable res is attaching to the NewsLst. How can I correct my error?

How to get the MAC Address of any android phone?

I've seen this LINK on how to get the MAC Address of an android phone but in my case I need to do it in javascript or asp.net mvc3. I Managed to get the MAC Address of the PC through MVC3 and my problem 1 is solve. This is my second problem in android phones.

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo wInfo = wifiManager.getConnectionInfo();
String macAddress = wInfo.getMacAddress();