Category Archives: Web Forms

Web Forms

[RESOLVED]Reading CSV file for validation and after that saving it on server in MVC 4

Hi,

I have CSV file upload functionality in MVC4. Below my code is working fine on local machine, when I deploy same code on server I am getting error "Could not find file at C:WindowsSystem32InetSrv".

  [HttpPost]
        public ActionResult Upload(HttpPostedFileBase UploadedFile)
        {
            try
            {
                var fp = Path.GetFileName(UploadedFile.FileName);
                var reader = new StreamReader(UploadedFile.FileName);
                while (!reader.EndOfStream)
                {

                        string[] str = reader.ReadLine().Split(‘,’);  //Validation Logic.

                 }

                reader.Close();
                reader.Dispose();
                UploadedFile.SaveAs(@"d:FileUploadDemo" + fp);
                return View("Index");
            }
            catch (Exception)
            {
                return View("Index");
            }
        }

But If I comment below file reading code,

  var fp = Path.GetFileName(UploadedFile.FileName);
                var reader = new StreamReader(UploadedFile.FileName);
                while (!reader.EndOfStream)
                {
                    string[] str = reader.ReadLine().Split(‘,’);
                }
                reader.Close();
                reader.Dispose();

then my file is getting saved on the server perfectly fine.

But, Before saving a file, I want to validate the file data. I have implemented client side code but it is not working in IE browsers. So wanted to do server side validation.

Or any client side code, working in IE8+ browsers (without asking user to activate ActiveX object) is greatly appreciated.

The filename only contains the name of the file itself, it is for "information" purposes, the file isn’t actually saved to disc until you save it using SaveAs, so you can’t access it yet via StreamReader.  If you want to read its contents you need to access
the file data via the InputStream and convert it to a string that you can then validate

http://stackoverflow.com/questions/16030034/asp-net-mvc-read-file-from-httppostedfilebase-without-save

[RESOLVED]Bind IDictionary List to MVC WebGrid

I’m dont know how to bind an IDictionary list to a MVC WebGrid. This is what I have so far

 public List<IDictionary> GetAddress()
        {
            List<IDictionary> names = new List<IDictionary>();
        //List<string> names = new List<string>();
            using (MVCDBEntities example = new MVCDBEntities())
            {
                var Uus = from U1 in example.Users where U1.Name != null select U1;
                names = Uus.OfType<IDictionary>().ToList();
            }
            return names;
        }

I now need to some how bind  this to a webgrid, how would I achieve this ?

Hi,

taken from

http://forums.asp.net/t/1719060.aspx?Binding+MVC3+webgrid+from+DataTable+AsEnumerable+:

Model method:

public List<IDictionary> FetchEmployeeDetails()
         {
             DataSet dsEmployee = new DataSet();
             DbCommand dbCmd = m_DbAccess.SqlDb.GetStoredProcCommand("Test_FetchEmployeeDetails");
             dbCmd.CommandType = CommandType.StoredProcedure;
             dsEmployee = m_DbAccess.SqlDb.ExecuteDataSet(dbCmd);

             return ConvertToListDictionary(dsEmployee.Tables[0]);
         }

Controller Code:

public ActionResult FetchDataForGrid()
         {
             EmployeeModels modelObject = new EmployeeModels();
             var resultSet = modelObject.FetchEmployeeDetails();
             return View(resultSet);
        }

View Code:

@using System.Dynamic
 @model List<System.Collections.IDictionary>
 @{
     var result = new List<dynamic>();

     foreach (var emprow in Model)
     {
         var row = (IDictionary<string, object>)new ExpandoObject();
         Dictionary<string, object> eachEmpRow = (Dictionary<string, object>)emprow;

         foreach (KeyValuePair<string, object> keyValuePair in eachEmpRow)
         {
             row.Add(keyValuePair);
         }
         result.Add(row);
     }
     var grid = new WebGrid(result);
 }

 @if (@Model != null)
 {
     @grid.GetHtml(tableStyle: "grid", headerStyle: "head", alternatingRowStyle: "alt");
 }

Grz, Kris.

Thanks for the reply, I am just getting an error with the IDictionary list anyways thanks for your time.  Is there anyway you can just use a asp.net Gridview control with something like this with the entity framework ? As binding data to a webgrid in mvc
is a joke, so much extra work, in php its easier than this

Hi,

you can’t really make use of the gridview in MVC.

What you can do, and what I did in the past, is make use of jqGrid and bind the grid client side. There are also commercial tools for this like KendoUI and others.

Grz, Kris.

[RESOLVED]why my helper havent any output after run !!!!!!

Hi dear,

I‘ve created
a method and
run it
. But
this method
does not
output
. So I
trace the code
and found
the body of a method
is not implemented.
I do not know
why
.
Please give me
what’s problem.

my code:

 @helper SetName(string name)
                {
                          string first_name = name;
                          <label>@first_name</label>
                      
    
                }
---------------run helper ----
  SetName("asp.net");

 

how can i solve this problem

 @helper SetName(string name)
 {
     <label>@name</label>
 }

That should be all you need. If you want it to render, you should call it like this (prefix with @):

@SetName("asp.net")

Mikesdotnetting

 @helper SetName(string name)
 {
     <label>@name</label>
 }

That should be all you need. If you want it to render, you should call it like this (prefix with @):

@SetName("asp.net")

thank you very veryyyy much Mikesdotnett

How to iterate model and save to database?

How can you iterate through a single model and save it multiple times so that a new record/row is created in the database?

For example I have an application form and I wish to create multiple applications using the same details but for each application I will change the applicant.

I have the following controller action to which attempts to achieve this:

public ActionResult Create([Bind(Prefix = "Application")]Application application, FormCollection collection)
{

List<string> selectedEmployees = new List<string>();

// Application.EmpIDs is a multiselect drop down list
if (collection["Application.EmpIDs"] == null)
{
	ModelState.AddModelError("Employee", "Please select an employee");
}
else
{
	selectedEmployees.AddRange(collection["Application.EmpIDs"].Split(',').ToList());
}



if (ModelState.IsValid)
{

   
   foreach (var item in selectedEmployees)
   {
	// Add emp id
	application.EmpID = Convert.ToInt32(item);
                           
                            
	// Add Application
	_repository.AddApplication(application);

	// Persist changes back to database
	_repository.Save();

	

    }
}

//...more stuff

}

however i end up with the following error message:

An object with the same key already exists in the ObjectStateManager. The existing object is in the Modified state. An object can only be added to the ObjectStateManager again if it is in the added state.

It sounds like the object you are looking for already exists within your context. Have you tried removing the AddApplication() call and just calling the Save() (or SaveChanges()) method on it’s own? If Entity Framework is tracking your elements,
then it will track changes (such as new or updated property values) which will be saved to the database when the Save method is called :

// Add emp id
application.EmpID = Convert.ToInt32(item);
                           
// Persist changes back to database
_repository.Save();

You might also want to consider taking a look at the data within your database to be sure that you don’t have any issues or duplicate keys (or any logical issues that could cause that to occur).

the AddApplication() call simply updates some additional property values. The full method is below:

public void AddApplication(Application application)
{
            application.StatusID = 1;
            application.CreatedDate = DateTime.Now;
            application.LastModifiedDate = DateTime.Now;
            application.StatusDate = DateTime.Now;

            _entities.Applications.AddObject(application);

}

there should be no issues with the database becuase each application has an autoincrement primary key.

ok i’ve managed to get this working by adding the following line after the save method:

// Detach the entity from object context
_repository.Detach(application);

However I need get the ids of all the newly added applications. I have added the following list below the save method but all i get added into this list is the first application multiple times hence i end up with the same application id.

// Persist changes back to database
_repository.Save();

// create list of applications added to reference new application ids
// this is basically a list  List<Application> applicationsSubmitted = new List<Application>();
applicationsSubmitted.Add(application);
// Detach the entity from object context 
_repository.Detach(application);

[RESOLVED]how can i use url.action in @helper method ?

Hi dear ,

 I create a @helper method and use @Url.Action helper in it.(in App_Code Folder)

@helper GetNews(int CategoryID, int Rows)
{
         <div class="@Style" id="@CategoryID">
         
                  <a style="padding-right:10px" href="@Url.Action("Rss", "Home", new { type="News" , cid = CategoryID})"><img src="@Url.Content("~/images/icon/rss.png")" /></a>
                                &nbsp;
                                <a href="@Url.Action("Details", "News", new { cid=CategoryID,sid=Model})">arshive</a>
                             </div>
                        
}

after run i get an error :

Compilation Error 
  Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 

 Compiler Error Message: CS0103: The name 'Url' does not exist in the current context

Source Error:


 

Line 193:                                </table>*@
Line 194:
Line 195:                                <a style="padding-right:10px" href="@Url.Action("Rss", "Home", new { type="News" , cid = CategoryID})"><img src="@Url.Content("~/images/icon/rss.png")" /></a>
Line 196:                                &nbsp;
Line 197:                                <a href="@Url.Action("Details", "News", new { cid=CategoryID,sid=Model})">arshive</a>
 

Also,
I had
to have
a class named ExtensionMethodHelper
for create external helpers and use it ( in Model folder ).but i
can not call
this
external helpers on the page(.cshtml) that
I’ve created
in
App_Code folder.

in fact after write @Html.  i dont find my favorite external helper (in ExtensionMethod class in Model folder).

for e.g : Html.PersianDate made in ExtensionMethodHelper in Model Folder

   <span class="date">@Html.ToPersianDate(item.DateToShow)</span>

in :

below helper create in App_Code

@helper GetNews(int CategoryID, int Rows)
{
       <div class="@Style" id="@CategoryID">
                <a style="padding-right:10px" href="@Url.Action("Rss", "Home", new { type="News" , cid = CategoryID})"><img src="@Url.Content("~/images/icon/rss.png")" /></a>
                       &nbsp;
                   <a href="@Url.Action("Details", "News", new { cid=CategoryID,sid=Model})">arshive</a>
       </div>
                        
}

 how can i solve it

please help me

thanks

I use the "UrlHelper" class to do this.  Here’s a helper I always used in my projects (prior to bundles).  Use it as an example to expand on your own:

// file name is "Content.cs" stored in App_Code folder

@using System.Web.Mvc; @helper Script(string scriptName, UrlHelper url) { <script type="text/javascript" src="@url.Content("~/Scripts/" + scriptName)"></script> }

the helper in my View then looks like:

@Content.Script("jquery-1.10.1.min.js", Url)

You can see that I pass the "Url" to the helper.  Your helper would then look like…

@helper GetNews(int CategoryID, int Rows, UrlHelper url)
{
  ...

  <a href="@url.Action("Rss", "Home", ...)">

  ...
}

the "url" is lowercase fyi.  Don’t confuse it with Url

[RESOLVED]date formt isue c# and jquery

hello, I have a db with the  data attribute

and i’m using jquery date picker to insert date

in my computer I have no problem choosing and inserting but all users has report error: must be a date format

How can I fix it and what  wrong here ? 

code

in my class :

[DisplayFormat(DataFormatString = "{0:dd MMM }")]
           
public DateTime WeekFrom { get; set; }
        
[DisplayFormat(DataFormatString = "{0:dd MMM }")]

public DateTime? Until { get; set; }
 in my script 

$(function () {
    $(".date-picker").datepicker({ dateFormat: 'dd-mm-yy' });
})

my Sql look like this 
WeekForm (datetime not null)
Until(datetimee,null)

how  can I fix it and what is wrong  here?

Based on the current format you are using, you’ll likely need to change the format of your DatePicker to match :

$(".date-picker").datepicker({ dateFormat: 'dd MM' });

Additionally, another problem is that the ‘mm’ value you are using in your DateFormat actually denotes minutes instead of months. If you wanted to use months (which is likely), you’ll instead want to use the capitalized ‘MM’ instead :

$(".date-picker").datepicker({ dateFormat: 'dd-MM-yy' });

This should help to ensure that the formats coincide between your actual DisplayFormat attributes and the value contained in your DatePicker. Additionally, if you are using Chrome or the jQuery.validate library, you might want to look into
this known issue regarding DateTime objects being parsed or validated improperly.

Rion Williams

Based on the current format you are using, you’ll likely need to change the format of your DatePicker to match :

$(".date-picker").datepicker({ dateFormat: 'dd MM' });

Additionally, another problem is that the ‘mm’ value you are using in your DateFormat actually denotes minutes instead of months. If you wanted to use months (which is likely), you’ll instead want to use the capitalized ‘MM’ instead :

$(".date-picker").datepicker({ dateFormat: 'dd-MM-yy' });

This should help to ensure that the formats coincide between your actual DisplayFormat attributes and the value contained in your DatePicker. Additionally, if you are using Chrome or the jQuery.validate library, you might want to look into
this known issue regarding DateTime objects being parsed or validated improperly.

hello Rion, thanks,

using :

$(function () {
    $(".date-picker").datepicker({ dateFormat: 'dd-MM-yy' });
})
i'm getting in my page a date that look like this :"30-September-2014" and error MSG :" The field must be a date"

Oops. 

I appeared to get my ASP.NET and jQuery code mixed up. The lowercase format should be fine : 

$(function () {
    $(".date-picker").datepicker({ dateFormat: 'dd-mm-yy' });
})

Is there any chance that you are using any kind of validation-based scripts (like jQuery.validate)? Or is the error message you are receiving coming from the actual server-side code?

A

Rion Williams

Oops. 

I appeared to get my ASP.NET and jQuery code mixed up. The lowercase format should be fine : 

$(function () {
    $(".date-picker").datepicker({ dateFormat: 'dd-mm-yy' });
})

Is there any chance that you are using any kind of validation-based scripts (like jQuery.validate)? Or is the error message you are receiving coming from the actual server-side code?

thanks Rion for your time and help.  ,

it look fine on my side . i’ll check with users  to find out.

Problem fix . thanks Rion.

and yes this is Jquery validator.

[RESOLVED]Authorize Attribute

Hi All, 

I am writing my custom Authorize attribute..

but I need to initialize my service with two paramteres  which in turn calls the repository

How can I initialize service or repository ?

Please help 

Thanks

Hi,

gowrifor.net

How can I initialize service or repository ?

Can you show some relevant parts of your code? Are you using dependency injection? …

Grz, Kris.

gowrifor.net

I need to initialize my service with two paramteres

Do you mean to pass parameters to you custom Authorize attribute. In that case you can pass it as a parameter. Please take a look at this stack overflow post

create the authorize filter with parameter asp.net mvc

[RESOLVED]Re-using the same model, same controller with different views

I didn’t think that this was going to cause me so much difficulty .. and I have only just started with this project Surprised

I have one model which I want to populate the model’s properties over multiple views. I was planning on using the controller to determine which View should be displayed.

The model looks like this:

public class QC_Rework
{
    public int nViewToDisplay { get; set; }
    public int nReworkNumber { get; set; }
    public string cSecondaryReferenceType { get; set; }
    public string cSecondaryReferenceNumber { get; set; }
    public int nLineQuantity { get; set; }
}

My "Create" controller looks like this:

[HttpGet]
public ActionResult Create([Bind(Prefix = "ReworkNumber")] int ReworkNumber=0)
{

    var oQC = new QC_Rework();
    oQC.nReworkNumber = ReworkNumber;
    oQC.nViewToDisplay = 1;
    return View("GetSecondaryReferenceType2", oQC);

}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(QC_Rework oQC_Rework)
{
    // After GetSecondaryReferenceNumber2 the value of nViewToDisplay is "1"!!!
    // Even though the value in the Source Code and in the form says "2"!!!
    if (ModelState.IsValid)
    {
        switch (oQC_Rework.nViewToDisplay)
        {
            // Coming from Secondary Reference Type View
            case 1:
                if (String.IsNullOrEmpty(oQC_Rework.cSecondaryReferenceType) == true)
                {
                    ModelState.AddModelError("Model", "A secondary reference type needs to be selected!");
                    return View("GetSecondaryReferenceType2", oQC_Rework);
                }
                else
                {
                    oQC_Rework.nViewToDisplay = 2;
                    return View("GetSecondaryReferenceNumber2", oQC_Rework);

                }
            // Coming from Secondary Reference Type View
            case 2:
                {
                    oQC_Rework.nViewToDisplay = 3;
                    return View("GetQCDetails2", oQC_Rework);
                }
        }
    }
    // Should not get here at this stage!
    return View("NotFound", oQC_Rework);
}

The model’sproperty nViewToDisplay controls which Views get displayed.

When I debug the code, before the View GetSecondaryReferenceNumber2 gets called, the value in oQC_Rework.nViewToDisplay is set to 2 … but in the view itself it is "1′!!

What am I doing wrong?

Many thanks …

you don’t show the view code, but most likely its something like:

   @Html.HiddenFor(m=>m.nViewToDisplay)

with the html helpers, the lambda expression is just to get the name. ("nViewToDisplay") in your case. this name is then used to lookup the value. The postback form collection is searched before the ViewBag.Model (where you changed the data). so the postback
value is used.

just use a vanilla hidden field:

  <input type="hidden" name="nViewToDisplay" value="@Model.ViewBag.nViewToDisplay" />

or original helper that takes the value

   @Html.Hidden("nViewToDisplay",ViewBag.nViewToDisplay)