ViewBag for video upload? - c#

I am working with sample from codeproject http://www.codeproject.com/Tips/1011040/Upload-and-Delete-Video-File-to-Microsoft-Azure-Bl
I have created an index.cshtml in the way of
that is
#model List<string>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using (Html.BeginForm("Add", "Blob", FormMethod.Post, new
{enctype = "multipart/form-data" }))
{
<div>
<input type="file" name="pic" id="pic" />
<input type="submit" value="Upload Now" id="s1" />
</div>
}
<ul>
#foreach (var item in Model)
{
<li>
<input type="button" name="b1" id="b1"
value="Delete"
onclick="Remove('#item')" />
<video src="#item" height="200" width="200" controls />
</li>
}
</ul>
#section scripts{
<script>
function Remove(x) {
alert(x);
var uri = "/Blob/remove";
$.post(uri, { name: x }, function (y) {
window.location.href = "/blob/index";
alert(y);
});
}
</script>}
and my Controller class is :
public class BlobsController : Controller
{
//
// GET: /Blobs/
BlBlobs objbl = new BlBlobs();
public ActionResult Index()
{
//return View();
return View(objbl.GetBlobList());
}
[HttpPost]
public ActionResult Add(HttpPostedFileBase pic)
{
objbl.AddBlob(pic);
return RedirectToAction("Index");
}
[HttpPost]
public string Remove(string name)
{
objbl.DeleteBlob(name);
return "Blob Removed Successfully";
}
}
That give me pretty nice browse/upload form, but fails on upload click with 404 error. The question is - how to call the add method correctly in this index.cshtml file?

Your controller is called BlobsController so that would give you a route of /blobs/{action} with the default route, however in your view your actions are looking for a controller called blob. Either change the name of your controller
public class BlobController : Controller
{
//...
}
Or update your views to use the correct controller name.
Html.BeginForm("Add", "Blobs", FormMethod.Post, new
{enctype = "multipart/form-data" }))

Related

Post from Razor page clears Model values - when it shouldn't?

I have a simple single page ASP.NET Core Razor app that has a "select" in it that I am populating from a Model variable. The values in the Model variable are cleared by the time that I examine them in the OnPost() method. (The variable named machineModel returns just fine but the variable named machineModels in the Model is cleared by the Post.) What is doing this?
Here's what the Index.cshtml looks like:
#page
#model IndexModel
#{
ViewData["Title"] = "Home page";
}
<div class="text-left">
<form enctype="multipart/form-data" method="post">
Model: <select name="machineModel" asp-for="machineModel" asp-items="Model.machineModels" required></select>
<input type="submit" asp-page-handler="Download" value="Download certificate" />
</form>
</div>
Here's what the Index.cshtml.cs looks like:
[BindProperties]
public class IndexModel : PageModel
{
public string machineModel { get; set; }
public List<SelectListItem> machineModels = new List<SelectListItem>();
// In some other function in the class the machineModels variable is filled (several times) ...
string modelStr = reader.GetAttribute("value");
int numMachineModels = machineModels.Count;
string machineModelIndexStr = numMachineModels.ToString();
machineModels.Add(new SelectListItem { Text = modelStr, Value = machineModelIndexStr, Selected = true });
// And here's the Post method ...
public IActionResult OnPostDownload()
{
// Doesn't matter what's in here, machineModels is already cleared at this point
return Page();
}
}
Thanks in advance for any help you can provide,
Rich
You do not post the value of machineModels from view to hanlder, try to add below code in your form.
<form enctype="multipart/form-data" method="post">
<div>
#{ int i = 0;}
#foreach (var x in Model.machineModels)
{
<input type="hidden" name="machineModels[#i].Text" value="#x.Text" />
<input type="hidden" name="machineModels[#i].Value" value="#x.Value" />
i++;
}
</div>
Model: <select name="machineModel" asp-for="machineModel" asp-
items="Model.machineModels" required></select>
<input type="submit" asp-page-handler="Download" value="Download
certificate" />
</form>
PageModel:
[BindProperty]
public List<SelectListItem> machineModels { get; set; } = new List<SelectListItem>();

Server side validation of form in partial with different model using Asp.Net MVC

View
#model List<Dal.IAdministrator>
#Html.Partial("PartialCreateAdmin", new ViewModels.AdministratorCreateModel())
Partial
#model ViewModels.AdministratorCreateModel
#using (Html.BeginForm("Insert", "Admin", FormMethod.Post, new { }))
{
<fieldset>
<br />
#Html.TextBoxFor(m => m.AccountName, new { placeholder = "Enter the account name here" })
#if (!ViewData.ModelState.IsValid)
{
<p style="color: darkblue;"> #ViewData.ModelState["AccountName"].Errors[0].ErrorMessage </p>
}
</fieldset>
<br />
<input type='Submit' value='Create' />
}
Controller:
[HttpPost]
public ActionResult Insert(AdministratorCreateModel vm)
{
// ...
if(!accountNameExists)
{
ModelState.AddModelError("AccountName", "Account name does not exist, please try again!");
return PartialView("PartialCreateAdmin", vm);
}
// ...
}
Currently If the validation fails, it returns to the partial, but I want to return the view, with the message along the form?
How can I do this?

MVC submit form more than once

I have come across a weird issue, I hope someone can explain why the following is happening.
My controller:
MasterModel main = new MasterModel();
public ActionResult Index()
{
return View();
}
[HttpGet]
public ActionResult VehicleDetail()
{
pageSessionSetup();
return PartialView("VehicleDetail", main.Vehicle);
}
[HttpPost]
public ActionResult VehicleDetail(VehicleDetailDisplay model)
{
ModelState.AddModelError("", "Errors occured");
main.Vehicle = model;
pageSessionSetup();
return PartialView("VehicleDetail", main.Vehicle);
}
Updated With View
My View:
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
#using (Ajax.BeginForm("VehicleDetail", "Operator", null, new AjaxOptions
{
UpdateTargetId = "VehicleDetail",
InsertionMode = InsertionMode.Replace,
HttpMethod = "Post"}, new { id = "VehicleDetail" }))
{
#Html.Partial("_ValidationSummary", ViewData.ModelState)
<div class="panel panel-default panel-body">
...
</div>
<div class ="col-lg-7 col-md-7 col-sm-7 col-xs-7 row">
<button type="submit" value="Save" class="btn btn-lg btn-green col-lg-2 col-md-5 col-sm-7 col-xs-7">Save</button>
</div>
}
And on my partial view I have a submit button, but when I click the submit button one time then the form gets submitted more than one time.
UPDATE:
use Html.BeginForm("ActionName", "ControllerName", FormMethod.Post) instead of Ajax.BeginForm() OR check if you have included the jquery.unobtrusive-ajax.min.js twice in your page(s)(in partial views also).
--------------------------------------------------------------------------------------------------------
#using (Html.BeginForm("ActionName", ""ControllerName", FormMethod.Post))
{
<label>SomeLabel</label>
...
<input type="submit" value="Button" /></p>
}

Get Textarea value from posted form in MVC3

This is my form
#using (Html.BeginForm("EditPayments", "BookingPathLabelsCms"))
{
if (#Model.DisplayName == "Payment Labels")
{
<textarea id="seeit" name="seeit" rows="5" cols="10"></textarea>
<textarea id="seeitNoSelect" name="seeitNoSelect" rows="5" cols="10"></textarea>
<div class="cmsButtonContainer">
Cancel it
<input type="submit" name="Save" value="Save it"#* onmouseover="copyto();"*# />
</div>
}
}
And this is my controller action
public ActionResult EditPayments(BookingPathLabelsCmsViewModel model)
{
string txtarea = Request.Form["seeit"];
return RedirectToAction("Index");
}
Am not getting the values of textareas here,but values in the breakpoint ,see image.
Your code should looks like:
#using (Html.BeginForm("EditPayments", "BookingPathLabelsCms"))
{
if (#Model.DisplayName == "Payment Labels")
{
#Html.TextBoxFor(m => m.SeeIt)
#Html.TextBoxFor(m => m.SeeItNoSelect)
<div class="cmsButtonContainer">
Cancel it
<input type="submit" name="Save" value="Save it"#* onmouseover="copyto();"*# />
</div>
}
}
Of course, your ViewModel BookingPathLabelsCmsViewModel should have SeeIt and SeeItNoSelect properties. After that, MVC will bind correctly entered data.
First create a class with property.
public class TextAreaProperty
{
public string MyTextAreaValue { get; set; }
}
Use on the view declare like:
#model <project_name>.Models.<Class_name>
In this case:
#model MvcApplication1.Models.TextAreaProperty
Use this textArea Razor
#Html.TextAreaFor(x=> x.MyTextAreaValue)
On method post receiving parameter type TextAreaProperty
[HttpPost]
public ActionResult Index(TextAreaProperty textAreaProperty)
{
return View();
}
You will get the value from textAreProperty.

I can't send my model in my controller

I have a problem to send my Model into my controller.
I use a button with the ajax to change the page but i need the model who is the first page to the second page.
I would like send my model in my controller but it's not work.
When i come in the page CreateAll, the renderpartial follow works to display Step1 but if i click on the step2 i would like the mainModel to be send to my controller use a partial view with submodel.
My model is:
public class CreateAllStep
{
public CreateStep1 Step1 { get; set; }
public CreateStep2 Step2 { get; set; }
public CreateAllStep(CreateStep1 step1, CreateStep2 step2)
{
this.Step1 = step1;
this.Step2 = step2;
}
}
My controller is(when the page start):
public ActionResult Create()
{
CreateStep1 step1=FillStep1();
CreateStep2 step2 = FillStep2();
CreateAllStep allStep = new CreateAllStep(step1, step2);
return View(allStep);
}
My controller is(when i click on the button, it's here where i would like send the model):
[HttpPost]
public ActionResult Create(String btn, CreateAllStep form)
{
if (Request.IsAjaxRequest())
{
if (btn != null)
{
if (btn == "Step1")
{
return PartialView("Step1",form.Step1);//not work
}
else if (btn == "Step2")
{
return PartialView("Step2");//work
}
else if(btn =="AllStep")
{
return PartialView("AllStep");
}
}
}
return View();
}
And my main view is :
#model SiteWebEmpty.Models.CreateAllStep
#{
ViewBag.Title = "Title";
}
<script type="text/javascript">
$(function () {
$('form').submit(function () {
$.post(this.action, $(this).serialize(), function (data) {
alert(data);
});
return false;
});
});
</script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<h2>Title</h2>
#using (Ajax.BeginForm("Create", //controller action name
"CreateStep", //controller name
new AjaxOptions //ajax options that tell mvc how to perform the replacement
{
UpdateTargetId = "ViewPage", //id of div to update
HttpMethod = "Post" //how to call the controller action
}, new { id = "FormName" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Create </legend>
<button type="submit" name="btn" value="Step1" id="Step1">Step 1</button>
<button type="submit" name="btn" value="Step2" id="Step2">Step 2</button>
<button type="submit" name="btn" value="AllStep" id="AllStep">All Step</button>
<div id="ViewPage">
#Html.Partial("Step1", Model)
</div>
</fieldset>
}
My partial view is:
#model SiteWebEmpty.Models.ArticleRequest.CreateArticle.ArticleRequestDisplayCreateAllStep
<fieldset>
<legend>Step 1</legend>
#Html.LabelFor(step1 => step1.Step1.Customer)
#Html.EditorFor(step1 => step1.Step1.Customer)
#Html.ValidationMessageFor(step1 => step1.Step1.Customer)
#Html.LabelFor(articleType => articleType.Step1.ArticleType)
#Html.DropDownList("ArticleType", Model.Step1.ArticleType)
#Html.ValidationMessageFor(articleType => articleType.Step1.ArticleType)
#Html.LabelFor(model => model.Step1.LabelType)
#Html.DropDownList("LabelType", Model.Step1.LabelType)
#Html.ValidationMessageFor(model => model.Step1.LabelType)
</fieldset>
render html:
<script src="/Scripts/jquery.unobtrusive-ajax.min.js" type="text/javascript"></script>
<h2>Title</h2>
<form action="/CreateStep/Create?Length=13" data-ajax="true" data-ajax-method="Post" data-ajax-mode="replace" data-ajax-update="#ViewPage" id="FormName" method="post"> <fieldset>
<legend>Create </legend>
<button type="submit" name="btn" value="Step1" id="Step1">Step 1</button>
<button type="submit" name="btn" value="Step2" id="Step2">Step 2</button>
<button type="submit" name="btn" value="AllStep" id="AllStep">All Step</button>
<div id="ViewPage">
<fieldset>
<legend>Step 1</legend>
<label for="Customer">Customer</label>
<input class="text-box single-line" data-val="true" data-val-required="Customer is required" id="Customer" name="Customer" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Customer" data-valmsg-replace="true"></span>
<label for="ArticleType">Article Type</label>
<select data-val="true" data-val-required="ArticleType is required" id="ArticleType" name="ArticleType"><option value="127">AR1 : New Product</option>
<option value="161">AR2 : Product Modification</option>
</select>
<span class="field-validation-valid" data-valmsg-for="ArticleType" data-valmsg-replace="true"></span>
<label for="LabelType">Label Type</label>
<select data-val="true" data-val-required="LabelType is required" id="LabelType" name="LabelType"><option value="129">Private Label</option>
</select>
<span class="field-validation-valid" data-valmsg-for="LabelType" data-valmsg-replace="true"></span>
</fieldset>
</div>
</fieldset>
</form>
Thanks for your help :) !
Could you post the final HTML?
I think that your #Html.Partial("Step1", Model.Step1) will render a input text with id like Customer or ArticleType instead of Step1.Customer and Step1.ArticleType. What will bind to CreateAllStep.Customer that doesn´t exist.
If you have the Headers sent by the browsers will help too.
Update: Change your partial Step1, to accept a CreateAllStep Model and try again
Try removing your constructor on your ViewModel:
public CreateAllStep(CreateStep1 step1, CreateStep2 step2)
{
this.Step1 = step1;
this.Step2 = step2;
}
And change the controller code to:
public ActionResult Create()
{
CreateAllStep allStep = new CreateAllStep{Step1 = FillStep1(), Step2 = FillStep2()};
return View(allStep);
}
I have run into issues with constructors with parameters when databinding.

Categories