Click here to Skip to main content
15,881,413 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello All,

I'm Trying to upload Image with other details along with other details , but it gives me this error :-

C#
String[4]: the Size property has an invalid size of 0.


Stored Procedure is:-

SQL
ALTER proc [dbo].[spInsertPageDetail]
@Heading varchar(100),
@Body varchar(2000),
@Img varchar(100),
@PageName varchar(50),
@output char(1) output
As
Begin Transaction

set @output='F'

if(@PageName='WhyUsCreate')
Begin
	set @output='T'
	Insert into TblWhyUs(Heading,Body,Img) values (@Heading,@Body,@Img)
	if(@@error<>0)
	Begin
		rollback transaction
		return 0
	End	
End

if(@PageName='ProductCreate')
Begin
	set @output='T'
	Insert into TblProduct(Heading,Body,Img) values (@Heading,@Body,@Img)
	if(@@error<>0)
	Begin
		rollback transaction
		return 0
	End	
End

if(@PageName='SensorCreate')
Begin
	set @output='T'
	Insert into TblSensor(Heading,Body,Img) values (@Heading,@Body,@Img)
	if(@@error<>0)
	Begin
		rollback transaction
		return 0
	End	
End


commit
return 1


C#
My Model Is:-

namespace RsbEngMvc.Models
{
    [Table("TblWhyUs")]
    public class WhyUs
    {
        public int ID { get; set; }
        [Required]
        public string Heading { get; set; }
        [Required]
        public string Body { get; set; }
        [Display (Name="Image")]
        public string Img { get; set; }
    }
}


What I have tried:

My Controller is:-

public void Create(string Heading, string Body,string Img, string PageName)
{
string ConnectionString = ConfigurationManager.ConnectionStrings["RsbEnggContext"].ConnectionString;

using (SqlConnection con = new SqlConnection(ConnectionString))
{
SqlCommand SqlCmdCreate = new SqlCommand("spInsertPageDetail", con);
SqlCmdCreate.CommandTimeout = 0;
SqlCmdCreate.CommandType = CommandType.StoredProcedure;

SqlParameter SqlParamHeading = new SqlParameter("@Heading", System.Data.SqlDbType.VarChar, 100);
SqlParameter SqlParamBody = new SqlParameter("@Body", System.Data.SqlDbType.VarChar, 2000);
SqlParameter SqlParamImg = new SqlParameter("@Img", System.Data.SqlDbType.VarChar, 100);
SqlParameter SqlParamPageName = new SqlParameter("@PageName", System.Data.SqlDbType.VarChar, 50);
SqlParameter SqlParamOutput = new SqlParameter("@Output", System.Data.SqlDbType.Char);
SqlParamOutput.Direction = ParameterDirection.Output;

SqlCmdCreate.Parameters.Add(SqlParamHeading);
SqlCmdCreate.Parameters.Add(SqlParamBody);
SqlCmdCreate.Parameters.Add(SqlParamImg);
SqlCmdCreate.Parameters.Add(SqlParamPageName);
SqlCmdCreate.Parameters.Add(SqlParamOutput);

SqlParamHeading.Value = Heading.Trim();
SqlParamBody.Value = Body.Trim();
SqlParamImg.Value = Img.Trim();
SqlParamPageName.Value = PageName.Trim();

con.Open();
int Result = SqlCmdCreate.ExecuteNonQuery();

if (SqlCmdCreate.Parameters["@Output"].Value.ToString() == "F")
{
Response.Write("No Such Page Exist in Database. Contact Support!!");
}

else
{
if (Result > 0)
{
RedirectToAction("AdminWhyUs");
}

else
{
RedirectToAction("Error");
}
}
}
}

private bool IsValid(string UserName, string Password)
{
bool IsValid = false;

using (var db = new RsbEngMvc.Models.RsbEnggContext())
{
var user = db.login.FirstOrDefault(u => u.AdminUserName == UserName);

if (user != null)
{
if (user.AdminPassword == Password)
{
IsValid = true;
}
}
}

return IsValid;
}

[HttpGet]
public ActionResult AdminWhyUs()
{
string ConnectionString = ConfigurationManager.ConnectionStrings["RsbEnggContext"].ConnectionString;
List<whyus> whyuss = new List<whyus>();

using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
SqlCommand SqlCmdList = new SqlCommand("Select ID,Heading,Body,Img from TblWhyUs", con);
SqlCmdList.CommandTimeout = 0;
SqlDataReader SqlDrList = SqlCmdList.ExecuteReader();

while (SqlDrList.Read())
{
WhyUs whyusobj = new WhyUs();
whyusobj.ID = Convert.ToInt32(SqlDrList["ID"]);
whyusobj.Heading = SqlDrList["Heading"].ToString();
whyusobj.Body = SqlDrList["Body"].ToString();
whyusobj.Img = SqlDrList["Img"].ToString();
whyuss.Add(whyusobj);
}

return View(whyuss);
}

}

[HttpGet]
[ActionName("AdminWhyUsCreate")]
public ActionResult AdminWhyUsCreate_Get()
{
return View();
}

[HttpPost]
[ActionName("AdminWhyUsCreate")]
public ActionResult AdminWhyUsCreate_Post(FormCollection formCollection,HttpPostedFileBase file)
{
if (ModelState.IsValid)
{


WhyUs whyuss = new WhyUs();

if (file != null)
{
file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName);
//whyuss.Img = file.FileName;
}
//RsbEnggContext DbContext = new RsbEnggContext();
//DbContext.whyus.Add(whyuss);
//DbContext.SaveChanges();

string Heading = formCollection["Heading"];
string Body = formCollection["Body"];
string Img = Convert.ToString(file.FileName);
string PageName = "WhyUsCreate";

Create(Heading, Body,Img, PageName);


return RedirectToAction("AdminWhyUs");
}

return View();
}

}

My View Is :-


Create for WhyUs Page



@*@using (Html.BeginForm())*@
@using (Html.BeginForm("AdminWhyUsCreate", "MyAdmin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{

@Html.AntiForgeryToken()
@Html.ValidationSummary(true)


Create New Entry in WhyUs


@Html.LabelFor(model => model.Heading)


@Html.TextBoxFor(model => model.Heading, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.Heading)



@Html.LabelFor(model => model.Body)


@Html.TextAreaFor(model => model.Body, new { @class = "form-control", @rows = 5 })
@Html.ValidationMessageFor(model => model.Body)



@Html.LabelFor(model => model.Img)


@*@Html.EditorFor(model => model.Img)*@
@*@using (Html.BeginForm("Upload", "Upload", FormMethod.Post, new { cssclass = "btn btn-info", enctype = "multipart/form-data" }))*@
{
<input type="file" id="FileUpload" name="file" />
@Html.ValidationMessageFor(model => model.Img)
}



<input type="submit" value="Create" class="btn btn-dark" />



}


@Html.ActionLink("Back to List", "AdminWhyUs")




Whenever I click the Create Button It Gives the error :-

String[4]: the Size property has an invalid size of 0.
Posted
Updated 25-Jan-23 19:34pm

1 solution

Finally I found the Solution :-

Controller :-
C#
public ActionResult AdminProductCreate_Post(Product products, HttpPostedFileBase file)
       {
           if (ModelState.IsValid)
           {
               if (file != null)
               {
                   file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName);
                   products.Img = file.FileName;
               }


               RsbEnggContext DbContext = new RsbEnggContext();
               DbContext.product.Add(products);
               DbContext.SaveChanges();

               return RedirectToAction("AdminProduct");
           }

           return View();
       }


And View:-

HTML
<div class="container">
    <h2 style="color:yellowgreen"><b>Create for Product Page</b></h2>

    @using (Html.BeginForm("AdminProductCreate", "MyAdmin", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)

        <fieldset>
            <legend>Create New Entry in Products</legend>

            <div class="editor-label">
                @Html.LabelFor(model => model.Heading)
            </div>
            <div class="editor-field">
                @Html.TextBoxFor(model => model.Heading, new { @class = "form-control", maxlength = "100" })
                @Html.ValidationMessageFor(model => model.Heading, "", new { @class = "label label-danger" })
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.Body)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.Body, new { @class = "form-control", @rows = 5, maxlength = "3000" })
                @Html.ValidationMessageFor(model => model.Body, "", new { @class = "label label-danger" })
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.Img)
            </div>
            <div class="editor-field">
                <input type="file" id="FileUpload" name="file" />
            </div>

            <p>
                <input type="submit" value="Create" class="btn btn-dark" />
            </p>
        </fieldset>
    }

    <div>
        @Html.ActionLink("Back to List", "AdminProduct")
    </div>
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900