I have a form for adding Books in a database,
I Have a modal window in my form to create a Publisher, if the specified format doesn't exist in Publisher Dropdown, I Create my Modal in a partial view for add Publisher,
this is my view:
#model WebApplication3.Models.BookModel
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="CustomerList"></div>
<h2>Create New Book</h2>
<label class="text-#ViewBag.ClassName">
#ViewBag.Message
</label>
#using (Html.BeginForm("CreateBook", "Book", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.TitleID, "TitleID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("TitleID", null, "Select a Title", htmlAttributes: new { #class = "form-control" })
#Html.ActionLink("Add New", "Create", "Title")
#Html.ValidationMessageFor(model => model.TitleID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FormatID, "FormatID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("FormatID", null, "Select a Format", htmlAttributes: new { #class = "form-control" })
<a href="" class="" data-toggle="modal" data-target="#FormatModal">
Add New
</a>
#Html.ValidationMessageFor(model => model.FormatID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ISBN, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ISBN, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ISBN, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Quantity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Quantity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Quantity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
</div>
}
<div class="modal fade" id="PublisherModal" tabindex="-1" role="dialog" aria-labelledby="publisherModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
#Html.Partial("_Publisher")
</div>
</div>
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/jqueryajax")
}
and this is my Publisher partial view:
#model WebApplication3.Models.PublisherModel
#using (Ajax.BeginForm("CreatePublisher", "Book", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "publisherForm", InsertionMode = InsertionMode.ReplaceWith }))
{
<div id="publisherForm">
<div class="modal-header">
<h5 class="modal-title" id="publisherModalLongTitle">Create New Publisher</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#Html.AntiForgeryToken()
<div class="form-horizontal">
<div class="form-group">
<span class="text-#ViewBag.ClassName">
#ViewBag.Message
</span>
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Value, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Value, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Value, "", 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.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
#Html.ActionLink("Manage", "Index", "Publisher", new { area = "" }, new { #class = "btn btn-link" })
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</div>
}
and this is my controller
[HttpPost]
[ValidateAntiForgeryToken]
public PartialViewResult CreatePublisher([Bind(Include = "ID,Value,Description")] PublisherModel publisherModel)
{
ViewBag.TitleID = new SelectList(repoTitle.GetModels(), "ID", "Title");
ViewBag.FormatID = new SelectList(repoFormat.GetModels(), "ID", "Value");
PublisherModel publisher = repoPublisher.GetModels().FirstOrDefault(x => x.Value == publisherModel.Value);
if (publisher == null)
{
if (ModelState.IsValid)
{
repoPublisher.Insert(publisherModel);
ViewBag.PublisherID = new SelectList(repoPublisher.GetModels(), "ID", "Value", publisherModel.ID);
ViewBag.Message = $"Publisher \"{publisherModel.Value}\" Added Successfully";
ViewBag.ClassName = "success";
return PartialView("_Publisher");
}
}
else
{
ViewBag.Message = $"Publisher \"{publisherModel.Value}\" Already Exsisted";
ViewBag.ClassName = "danger";
}
ViewBag.PublisherID = new SelectList(repoPublisher.GetModels(), "ID", "Value");
return PartialView("_Publisher",publisherModel);
}
How Can change to my code that if a new Publisher inserted to Database, the Publisher dropdown refresh and select newly inserted data as a selected item?
About question
I can't run your code locally.
These operations can be implemented through JS.
I can show my tools.
This is the function gif:
Solution:
Select and add options as a whole.
// index.cshtml
<div>
#await Component.InvokeAsync("AutoAddListValue")
</div>
//Component
#model List<string>
<h3>Default page</h3>
<div>
<div>
<p>Lists</p>
<select name="select" class="" id="ComponentSelectId" onclick="ComponentSelectClick()">
<option id="ComponentOptionId" style="width:auto">ComponentTest</option>
#if (Model.Count != 0)
{
int count = Model.Count();
for (int item = 0; item < count; item++)
{
<option id="option">#Model[item].ToString()</option>
}
}
</select>
</div>
<div>
<input id="ComponentTestJsInput" class="d-none" value="132323" type="text" />
<input id="ComponentBtnDisplay" value="Add" type="button" class="btn btn-primary" onclick="ComponentBtnDisplayClick()">
<input id="ComponentBtnAdd" value="Add" type="button" class="btn btn-primary d-none" onclick="ComponentBtnAddClick()">
</div>
</div>
Bind data for components.
public class AutoAddListValueViewComponent : ViewComponent
{
private readonly SchoolContext _context;
public AutoAddListValueViewComponent(SchoolContext context)
{
_context = context;
}
public async Task<IViewComponentResult> InvokeAsync(
int maxPriority, bool isDone)
{
string MyView = "Default";
var items = await GetListAsync();
return View(MyView, items);
}
public async Task<List<string>> GetListAsync()
{
return await _context.Test.Select(o => o.Name).ToListAsync();
}
}
Using JS code to realize page interaction.
var ComponentBtnDisplayClick = function () {
$('#ComponentBtnAdd').removeClass("d-none");
$('#ComponentTestJsInput').removeClass("d-none");
$('#ComponentBtnDisplay').addClass("d-none");
}
var ComponentBtnAddClick = function () {
//alert("666666");
$('#ComponentBtnAdd').addClass("d-none");
$('#ComponentTestJsInput').addClass("d-none");
$('#ComponentBtnDisplay').removeClass("d-none");
inputVal = $('#ComponentTestJsInput').val();
//alert(inputVal);
$.ajax({
url: '/Test/SaveInputValue',
data: {
name: inputVal
},
type: 'post',
async: true,
cache: false,
success: function (data) {
//alert(data.code);
var option = "<option id='ComponentOptionId'>";
option += inputVal;
option += "</option>";
$("#ComponentSelectId").append(option);
var obj = document.getElementById("ComponentSelectId");
obj[obj.length - 1].selected = true;
},
error: function () {
alert('fail');
}
});
}
Other code
Source Code
Related
Goal: I'm trying to make a page that has the user enter in an address, then click a button that will verify it with a FedEx API. With the new verified address (now with the extra postal code from FedEx), I want to have the user verify that the new address is correct using a modal popup all without reloading the page.
Issue: I'm having a problem where the partial isn't showing and I'm not sure what I'm doing wrong.
Here's the View:
#model AirmotionEcommerceWebsite.Models.Home.DeliveryAddressModel
#{
ViewBag.Title = "Shipping Address";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br />
<div class="container">
#Html.AntiForgeryToken()
<form class="form-horizontal">
<h4>Shipping Address</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<partial id="ValidateAddress"></partial>
<div class="form-group">
<h5>Name</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Attention To</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strAttnTo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strAttnTo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Street</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strStreet1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strStreet1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>Street 2</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strStreet2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strStreet2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<h5>City</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strCity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strCity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#{
IEnumerable<SelectListItem> dataItems = ViewBag.states;
}
<div class="form-group">
<h5>State</h5>
<div class="col-md-10">
#Html.DropDownListFor(model => model.State.IntStateId, dataItems, "-- Select --", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.State.IntStateId, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<h5>Zip</h5>
<div class="col-md-10">
#Html.EditorFor(model => model.strZip, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.strZip, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" class="btn btn-primary" data-ajax-method="get" data-toggle="ajax-modal" data-target="#ValidateAddress"
data-url="#Url.Action("GetValidationOnAddress", new { model = Model })">
Verify Address
</button>
</div>
</div>
</form>
</div>
<script>
$(function () {
var PlaceHolderElement = $('#ValidateAddress');
$('button[data-toggle="ajax-modal"]').click(function (event) {
event.preventDefault();
var url = $(this).data('url');
// get the form containing the submit button
var form = $(this).closest('form')
// serialize all the fields in the form
var model = form.serialize();
// the the request to the url along with the form (model) data
$.get(url, model).done(function (data) {
PlaceHolderElement.html(data);
PlaceHolderElement.find('.modal').modal('show');
$('#ValidateAddress').modal('show');
})
})
})
</script>
Here's the Controller:
[HttpGet]
public IActionResult GetValidationOnAddress(DeliveryAddressModel model)
{
FedexAPI fedexAPI = new FedexAPI();
List<string> listOfStreets = new List<string>();
listOfStreets.Add(model.strStreet1);
listOfStreets.Add(model.strStreet2);
var newAddress = fedexAPI.ValidateAddress(listOfStreets, model.strCity, model.State.StrStateCode, model.strZip, "US");
if (newAddress.customerMessages.Contains("INTERPOLATED.STREET.ADDRESS"))
{
// Address is not valid
model.ErrorMessage = "The address entered could not be found. Please double check your address. If issues perssist, please contact our office _________";
}
else
{
model.strStreet1 = newAddress.streetLinesToken[0];
if (newAddress.streetLinesToken.Count > 1)
model.strStreet2 = newAddress.streetLinesToken[1];
model.strCity = newAddress.city;
model.strZip = newAddress.postalCode;
}
return PartialView("_AddressValidationPartial", model);
}
And lastly here's the Partial View:
#model AirmotionEcommerceWebsite.Models.Home.DeliveryAddressModel
<div class="modal fade" id="ValidateAddress">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="ValidateAddressLabel">Validate Address</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="Create">
<div class="form-group">
#if (Model.ErrorMessage == null)
{
<h5>#Model.strName</h5>
#if (Model.strAttnTo != null)
{<h5>#Model.strAttnTo</h5>}
<h5>#Model.strStreet1</h5>
#if (Model.strStreet2 != null)
{<h5>#Model.strStreet2</h5>}
<h5>#Model.strCity</h5>
<h5>#Model.State.StrStateCode</h5>
<h5>#Model.strZip</h5>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Accept Changes</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Edit</button>
</div>
}
else
{
<h4>#Model.ErrorMessage</h4>
}
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" data-save="modal">Save Changes</button>
</div>
</div>
</div>
</div>
I checked the console and found it was not able to find my partial view. Quick file move and it's working now! Thanks to #viveknuna for helping me notice this!
I want to retrieve data from textbox, when I but Id in the textbox it will retrieve rest of data in in other textbox here is my code:
controller:
[HttpPost]
public ActionResult Contact(int id)
{
testEntities db = new testEntities();
List<Table_1> tb = db.Table_1.ToList();
var c = tb.Find(m => m.id == id);
return View(c);
}
view
<div class="form-horizontal">
<h4>Table_1</h4>
<hr />
<form id="myForm">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.depart, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.depart, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.depart, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" value="Create" class="btn btn-default" id="btnSubmit">press here</button>
</div>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function () {
debugger
var data = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "/Home/Contact",
data: data,
success: function (response) {
},
});
});
});
</script>
I use almost the same codes:
#model FormSubmitWebApplication.Models.Student
#{
ViewBag.Title = "Contact";
}
<div class="form-horizontal">
<h4>Table_1</h4>
<hr />
<form id="myForm">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" value="Create" class="btn btn-default" id="btnSubmit">press here</button>
</div>
</div>
</form>
</div>
#section scripts {
<script type="text/javascript">
$(document).ready(function () {
$("#btnSubmit").click(function () {
debugger
var data = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "/Home/Contact",
data: data,
success: function (response) {
},
});
});
});
</script>
}
The id could be passed to the controller.
Could you show the debug view in the controller?
I want to export my Viewmodel from my view to my controller which is receiving it in a method, this is my view:
#using Resources
#model MyProject.ViewModel.CertificationViewModel
#{
ViewBag.Title = Resources.titleCertificationList;
#section css
{
<link href="#Url.Content("~/layout/css/stylesformador.css")" rel="stylesheet" />
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
}
}
<div class="mainblock">
<div class="block-group">
<div class="ttitle title">#HIQResources.titleEdit</div>
</div>
#using (Html.BeginForm("Edit", "Certification", FormMethod.Post, new { id = "form1" }))
{
#Html.AntiForgeryToken()
<div class="md-content">
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Id)
<div class="form-group">
#Html.LabelFor(model => model.pdf, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#*<input type="file" name="file" />*#
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control inputForm", #type="file" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Code, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Code, new { htmlAttributes = new { #class = "form-control inputForm", #readonly = "readonly" } })
#Html.ValidationMessageFor(model => model.Code, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SelectedEntityId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.SelectedEntityId, Model.EntitiesDrop, htmlAttributes: new { #class = "form-control inputForm" })
#Html.HiddenFor(model => model.SelectedEntityId)
#Html.ValidationMessageFor(model => model.SelectedEntityId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StatusId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.DropDownListFor(model => model.StatusId, Model.StatusDrop, htmlAttributes: new { #class = "form-control inputForm" })
#Html.HiddenFor(model => model.StatusId)
#Html.ValidationMessageFor(model => model.StatusId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Result, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Result, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Result, "", new { #class = "text-danger"})
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Date, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Date, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Observation, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-8">
#Html.EditorFor(model => model.Observation, new { htmlAttributes = new { #class = "form-control inputForm" } })
#Html.ValidationMessageFor(model => model.Observation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-1">
<div class="col-md-8">
<table class="table table-bordered">
<tr>
<th class="col-md-2">
#Html.DisplayNameFor(model => model.FileName)
</th>
<th class="col-md-2">Ficheiro</th>
</tr>
#foreach (var item in Model.teste)
{
<tr>
<td>
#if (item.FileName == null)
{
<h5>Não existem ficheiros para esta certificação.</h5>
}
else
{
#Html.DisplayFor(modelItem => item.FileName)
}
</td>
<td>
#if (item.FileName == null)
{
<h5>Não existem ficheiros para esta certificação.</h5>
}
else
{
Download
#*Delete*#
<input type="submit" value="Edit" id="Delete" class="btn btn-default btn-sm btn-detail" />
}
#*#Html.ActionLink("Download", "Certification", "Download", new { id = Model.Id })*#
</td>
</tr>
}
</table>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-8">
<input type="submit" value="#HIQResources.buttonSave" class="btn btn-default btn-sm btn-detail" />
#Html.ActionLink(HIQResources.buttonBack, "CertificationList", new { id = Model.StudentId, nome = Model.StudentName }, new { #class = "btn btn-default btn-sm btn-edit" })
</div>
</div>
</div>
</div>
}
</div>
#section Scripts {
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
<script src="~/Scripts/HIQTrainingScripts/Certification/Edit.js"></script>
<script>
$("#Date").datepicker({ dateFormat: 'yy/mm/dd' });
$("#Delete").click(function () {
var vm = $('#Model').serialize();
alert(vm)
var token = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
url: "/Certification/Edit",
type: "POST",
data: {
__RequestVerificationToken: token,
vm: vm,
click: "deu",
},
sucess: function (result) {
alert("sucess");
}
});
});
</script>
}
This is the method in my controller:
[Authorize(Roles = "Admin, Staff")]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(CertificationViewModel vm, string click) {
if (click == "deu")
{
int lol = _servicesFactory.GetService<ICertificationManager>().DeleteFile(vm, GetLoggedUser());
return View(vm);
}
}
The value of my ViewModel comes always as null to my Jquery variable and I don't know why, because it should come with the info from the view to the controller in order for me, to execute my task.
Am I missing something ?
#model CommonLayer.ORDER
#{
ViewBag.Title = "Update";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h4>Update Order Status</h4>
<br />
#if (Model.OrderStatus != "Shipped")
{
using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.UserId)
<div class="form-group">
#Html.LabelFor(model => model.OrderId, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderId, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderStatus, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
<select class="form-control" name="OrderStatus">
<option value="Pending" id="pending">Pending</option>
<option value="Shipped" id="shipped">Shipped</option>
</select>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderDate, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderDate, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderNumber, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderNumber, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<form action="/order/update/#Model.OrderId" method="post" enctype="multipart/form-data">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn btn-primary" />
</div>
</div>
</form>
</div>
}
}
else
{
<h4>Order Has Been Shipped!</h4>
}
My submit button isn't working regardless of the correct syntax being used. When I press the button nothing happens, as if I haven't clicked it, no redirecting whatsoever.
Was working until yesterday. Did not change any code whatsoever regarding the form or corresponding controller.
This is the controller corresponding to the form.
[HttpGet]
[Authorize(Roles = "ADM")]
public ActionResult Update(Guid Id)
{
BusinessLayer.Orders order = new BusinessLayer.Orders();
return View(order.GetOrder(Id));
}
[HttpPost]
[Authorize(Roles = "ADM")]
public ActionResult Update(CommonLayer.ORDER order, Guid id)
{
BusinessLayer.Orders blorder = new BusinessLayer.Orders();
blorder.UpdateOrder(order);
return RedirectToAction("UpdateDetails", new {id=id});
}
Use below code, let us know if doesn't work
Added below line to pass the orderid
#Html.HiddenFor(model => model.OrderId)
Updated below line to call action of a controller
Html.BeginForm("update","order",FormMethod.Post)
Finally removed the unnecessary form tag
Removed antiforgerytoken from view as you are not checking in you action method.
If you want to add that then you need to add [ValidateAntiForgeryToken] after [httppost] of Update Action method
#model CommonLayer.ORDER
#{
ViewBag.Title = "Update";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h4>Update Order Status</h4>
<br />
#if (Model.OrderStatus != "Shipped")
{
using (Html.BeginForm("Update","Order",FormMethod.Post))
{
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.UserId)
#Html.HiddenFor(model => model.OrderId)
<div class="form-group">
#Html.LabelFor(model => model.OrderId, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderId, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderStatus, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
<select class="form-control" name="OrderStatus">
<option value="Pending" id="pending">Pending</option>
<option value="Shipped" id="shipped">Shipped</option>
</select>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderDate, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderDate, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderNumber, htmlAttributes: new { #style = "font-size:medium", #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderNumber, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Update" class="btn btn-primary" />
</div>
</div>
</div>
}
}
else
{
<h4>Order Has Been Shipped!</h4>
}
My problem is with file upload and Ajax. I have one form with form fields and upload function. I want user to select image from disc, click upload without redirect, display image below, fill in the forms, click create to save form into one table and image into another. The problem is that both upload and create buttons are submiting and I want upload to wait for the rest of the form. Is Ajax the best solution for this?
Here is my code:
View:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>sticenikSlika</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.sticenikId, "sticenikId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("sticenikId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.sticenikId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.vrijeme, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.vrijeme, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.vrijeme, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div class="form-horizontal">
<div class="form-group">
#using (Html.BeginForm("FileUpload", "UploadImage", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file" class="control-label col-md-2">Upload Image:</label>
<div class="col-md-10">
<span class="btn btn-default btn-file">
<input type="file" name="file" id="file" />
</span>
<input type="submit" value="Upload" class="submit btn btn-default" id="upload" />
</div>
}
</div>
</div>
Controller that posts to the database is default Entity framework stuff.
Controller UploadImage:
public ActionResult FileUpload(HttpPostedFileBase file)
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(
Server.MapPath("~/Content/images/profile"), pic);
file.SaveAs(path);
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
JavaScript:
<script>
$('#upload').click(function (e) {
e.preventDefault();
$.ajax({
url: '/UploadImage/FileUpload',
// not sure what to do
error: function () {
alert('Error');
}
});
});
</script>
When I click 'upload' it saves the image but not the form and when I click 'create' it saves the form but not the image. How to combine those two?
i cant help you in ajax, but if you would to use c#,
in your razor page put just one form which contains the data and the image, your form of course should like this
#using (Html.BeginForm("--", "--", FormMethod.Post,
new { enctype = "multipart/form-data" }))
and your controller:
public ActionResult FileUpload(HttpPostedFileBase file, YourModel model)
{
//here save your model
if (file != null)
{
//save file
}
}
#using (Html.BeginForm("FileUploadAndSaveData", "UploadImage", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>sticenikSlika</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.sticenikId, "sticenikId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("sticenikId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.sticenikId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.vrijeme, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.vrijeme, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.vrijeme, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.vrijeme, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.vrijeme, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.vrijeme, "", new { #class = "text-danger" })
</div>
</div>
</div>
<label for="file" class="control-label col-md-2">Upload Image:</label>
<div class="col-md-10">
<span class="btn btn-default btn-file">
<input type="file" name="file" id="file" />
</span>
<input type="submit" value="Save" class="submit btn btn-default" id="upload" />
</div>
}
</div>
Create new Action in UploadImage Controller
public ActionResult FileUploadAndSaveData(HttpPostedFileBase file,Model obj) {
FileUpload(HttpPostedFileBase file);/// function Call for Save Image
SaveData(obj); //Function Call for Save Data
}