Post to an external form from a controller in mvc5 - asp.net-mvc-5

I have a form in a mvc5 view with a button. I need to process this form in the controller and add a few more field values which is picked up from the controller and then posted to an external url.
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Deal</h4>
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.First_Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.First_Name, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.First_Name)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Last_Name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.Last_Name, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Last_Name)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" name="save" />
<input type="submit" value="Register Deal" class="btn btn-default" name="submit" />
</div>
</div>
Controller
public ActionResult Create([Bind(Include = "Id,Name,Company,Telephone,Fax,Email,Title,Status,OpportunityAmount,First_Name,Last_Name,City,State,Country,Zip")] Deal deal, String submit)
{
if (ModelState.IsValid)
{
// do some processing and submit to another external form
}
}
Any thoughts on how we can accomplish this ?
One use case would be
if an username is provided the user then i would need to query from database the first last name, age etc and submit it to registration form of another site

You can post using Web Request Method. E.g.
public void post()
{
string URL = "http://";
System.Net.WebRequest webRequest = System.Net.WebRequest.Create(URL);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
Stream reqStream = webRequest.GetRequestStream();
string postData = Request.QueryString; //you form data in get format
byte[] postArray = Encoding.ASCII.GetBytes(postData);
reqStream.Write(postArray, 0, postArray.Length);
reqStream.Close();
StreamReader sr = new StreamReader(webRequest.GetResponse().GetResponseStream());
string Result = sr.ReadToEnd();
}

Related

redirect List<Data> to a view after user has submitting a form

I have a form where the user enter his/her details.
#using (Html.BeginForm("Create","Coupons"))
{
<div class="row">
<div class="col-sm-8">
<div class="page-header">Generer Coupon</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(m => m.Student)
#Html.DropDownListFor(m => m.Student, new SelectList(Model.Students, "Id", "Name"), "", new { #class = "form-control input-lg" })
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(m => m.Price)
#Html.TextBoxFor(m => m.Price, new { #class = "form-control input-lg" })
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
#Html.AntiForgeryToken()
<div class="form-group">
#Html.LabelFor(m => m.NumberOfCoupons)
#Html.TextBoxFor(m => m.NumberOfCoupons, new {#class = "form-control input-lg"})
</div>
</div>
</div>
<div class="row">
<div class="col-sm-4">
<button class="btn btn-success btn-lg">Generer</button>
</div>
</div>
}
I redirect the view to the Create Method on CouponsController
[HttpPost]
public ActionResult Create(CouponViewModel viewModel)
{
if (!ModelState.IsValid)
{
var model = new CouponViewModel
{
Students = _context.Students.ToList()
};
return View("Index", model);
}
for (int i = 1; i <= viewModel.NumberOfCoupons; i++)
{
var coupon = new Coupon
{
CouponNumber = viewModel.CouponNumber,
ValidationCode = viewModel.ValidationCode(6),
Price = viewModel.Price,
StudentId = viewModel.Student,
DateTime = Convert.ToDateTime(DateTime.Now.ToString("yy-MMM-dd ddd"))
};
_context.Coupons.Add(coupon);
_context.SaveChanges();
}
var coupons = _context.Coupons
.Where(c => c.StudentId == viewModel.Student)
.Include(s => s.Student)
.ToList();
TempData["viewModel"] = coupons;
return RedirectToAction("GetCoupons");
}
here is the view i receive the tempdata to display on the view
[HttpPost]
public ActionResult GetCoupons()
{
Coupon coupon = TempData["viewModel"] as Coupon;
return View("Print", (IEnumerable<Coupon>)coupon);
}
I have been stucked for like 3 days. I don't know where im wrong
There are a couple of problems with your example. But you can eliminate them if you do some things differently.
[HttpPost]
public ActionResult Create(CouponViewModel viewModel)
{
return RedirectToAction("GetCoupons", new { studentId = viewModel.Student });
}
First, your redirected action needs to be marked [HttpGet]. You can also avoid TempData if you pass the id on the query string, then perform the lookup in the redirected action.
[HttpGet]
public ActionResult GetCoupons(int studentId)
{
var coupons = _context.Coupons
.Where(c => c.StudentId == studentId)
.Include(s => s.Student)
.ToList();
return View("Print", coupons);
}
TempData isn't wrong but it won't persist on a refresh. Sometimes you will pass sensitive data which makes it useful then. Your cast to a single Coupon isn't quite what you want -- Cast to a collection instead.
[HttpGet]
public ActionResult GetCoupons()
{
var coupons = TempData["viewModel"] as IEnumerable<Coupon>;
return View("Print", coupons);
}

Textboxes are different sizes

I created my controllers and views using scaffolded item but when I run my view in the program I can see that my textboxes are different sizes.How will I get it to all be the same size?
this is my view:
#model FCproject.Models.Purchase
#{
ViewBag.Title = "Edit2";
}
<h2>Edit2</h2>
#using (Html.BeginForm(new { OrderDate = Model.OrderDate }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Purchase</h4>
<hr />
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.PurchaseID)
<div class="form-group">
#Html.LabelFor(model => model.CustomerID, "Customer Cell", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CustomerID", String.Empty)
#Html.ValidationMessageFor(model => model.CustomerID)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DeliveryChoice, "DeliveryChoice", new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div>
<label>#Html.RadioButton("DeliveryChoice", true) Deliver my order to me</label>
</div>
<div>
<label>#Html.RadioButton("DeliveryChoice", false) I will pick up my order</label>
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderDueDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderDueDate)
#Html.ValidationMessageFor(model => model.OrderDueDate)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderTime, "Order Due Time", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderTime)
#Html.ValidationMessageFor(model => model.OrderTime)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderAdress1, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderAdress1)
#Html.ValidationMessageFor(model => model.OrderAdress1)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderAdress2, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderAdress2)
#Html.ValidationMessageFor(model => model.OrderAdress2)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderAdress3, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderAdress3)
#Html.ValidationMessageFor(model => model.OrderAdress3)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
here is a link to a picture of the screen as you can see it looks very messy because the textbox sizes are different, the 'Order Due Date' textbox is too thick the 'CustomerCell' textbox is too small, the 'Order Due Time' is too thick and short:
Edit screen link
The ASP.NET MVC project template uses bootstrap see (http://getbootstrap.com/)
for styling the HTML. The CSS file should be located at "Content\bootstrap.css".
Note that the view includes the following classes to style the form
<div class="form-horizontal">
<div class="form-group">
the submit button is styled using
<input type="submit" value="Save" class="btn btn-default" />
and some of the of the HtmlHelper Methods (such as LabelFor) contain code for additional styles that are added to the HTML.
For example
new { #class = "control-label col-md-2" }
in
#Html.LabelFor(model => model.CustomerID, "Customer Cell", new { #class = "control-label col-md-2" })
if you want to use bootstrap to style your form's controls, then you need to add the appropriate bootstrap CSS classes to the elements in the view.
Below are some examples (not related to your code) to style various elements with bootstrap.
To style a Drop-down list add,
Html.DropDownList("movieGenre", (SelectList)ViewBag.movieGenre, "All", new { #class = "form-control" })
this results in the following HTML with the class form-control:
<select class="form-control" id="movieGenre" name="movieGenre">
<option value="">All</option>
<option>Comedy</option>
<option>Western</option>
</select>
to style a textbox add
#Html.EditorFor(model => model.Genre, new { htmlAttributes = new { #class = "form-control" } })
to get output similar to
<input class="form-control text-box single-line" id="Genre" name="Genre" type="text" value="Comedy" />
you might also add the text-danger bootstrap CSS class to make the validation warning text red (or the color it's defined to be in the CSS file) like this:
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
To learn about bootstrap classes for form controls take a look at bootstrap's documentation.
To figure out where to place the new { #class = "form-control" } line in the HtmlHelpers take a look at its documentation (https://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper_methods(v=vs.118).aspx)
You can also add your own CSS file after bootstrap's CSS and style the elements (including width) by yourself, but if you use bootstrap this is not recommended.
Once you style the form elements with bootstrap, their width should be the same
(go to bootstrap's website and click on CSS then Forms for more information).

Using Automapper to map viewmodel to domain model returns nulls in POST action?

I have a entity model that records some employee information. I have a similar view model.
In my create action I create a new instance of the viewmodel and pass a few lists for dropdowns.
In my Create Post action I map using AutoMapper the returned view model to the entity model.
I am doing something wrong because the posted back data doesn't seem to contain any of the view model data. It just contains nulls.
Any ideas what I am doing wrong?
Controller
// GET: /TimeCreditEntries/Create
public ActionResult Create()
{
var Model = new TimeCreditEntryViewModel(); //Create a new viewmodel to hold the TimeCreditEntry
Model.StationList = new SelectList(getStations(), "StationId", "Code");
Model.AuthorisedEmployee = new SelectList(getEmployees(), "EmployeeId", "FullNameSurnameFirst");
Model.AuthorisedPayment = new SelectList(getPaymentTypes(), "PaymentTypeId", "Code");
return View(Model); //View is returned with model as parameter.
}
// POST: /TimeCreditEntries/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "TimeCreditEntryId,RecordedDate,TimeCreditDate,ShiftId,StationId,AuthorisingEmployeeId,AuthorisedEmployeeId,ModifiedDate")] TimeCreditEntryViewModel timeCreditEntry)
{
if (ModelState.IsValid)
{
Mapper.CreateMap<TimeCreditEntryViewModel, TimeCreditEntry>();
db.TimeCreditEntries.Add(Mapper.Map<TimeCreditEntryViewModel, TimeCreditEntry> (timeCreditEntry));
db.SaveChanges();
return RedirectToAction("Register"); }
ViewBag.AuthorisedEmployeeId = new SelectList(db.Employees, "EmployeeId", "Title", timeCreditEntry.AuthorisedEmployeeId);
ViewBag.AuthorisingEmployeeId = new SelectList(db.Employees, "EmployeeId", "Title", timeCreditEntry.AuthorisingEmployeeId);
ViewBag.ShiftId = new SelectList(db.Shifts, "ShiftId", "Code", timeCreditEntry.ShiftId);
return View(timeCreditEntry);
}
View
#model ATAS.Models.ViewModels.TimeCreditEntryViewModel
#{
ViewBag.Title = "Create";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<fieldset>
<legend>Request to use time credit</legend>
<div class="form-group">
<label class="col-md-2 control-label" for="AuthorisedEmployee">Who</label>
<div class="col-md-2">
#Html.DropDownListFor(model => model.AuthorisedEmployee, Model.AuthorisedEmployee, "Select Employee", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.AuthorisedEmployeeId)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TimeCreditDate, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.TimeCreditDate, new { #class = "datepicker", id = "vacation" })
#Html.ValidationMessageFor(model => model.TimeCreditDate)
</div>r
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="StationList">Where</label>
<div class="col-md-2">
#Html.DropDownListFor(model => model.StationList, Model.StationList, "Choose Station", new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label" for="Shift">Which</label>
<div class="col-md-2">
#Html.DropDownList("Shift", new SelectList(string.Empty, "Value", "Text"), new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<button class="btn btn-default" type="reset">Cancel</button>
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</div>
</fieldset>
</div>
}
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.datepicker').datepicker()
$("#Shift").prop("disabled", true);
//Dropdownlist Selectedchange event
$("#StationList").change(function () {
$("#Shift").empty();
if ($("#StationList").val() != "") {
$.ajax({
type: 'POST',
url: '#Url.Action("GetShiftsByStation")', // we are calling json method
dataType: 'json',
data: { selectedValue: $("#StationList").val() },
// here we are get value of selected Station and passing same value as input to json method GetShifts.
success: function (shiftList) {
// states contains the JSON formatted list
// of states passed from the controller
$("#Shift").append('<option value="' + null + '">' + "Choose shift" + '</option>');
$.each(shiftList, function (i, shift) {
$("#Shift").append('<option value="' + shift.Value + '">' + shift.Text + '</option>');
// here we are adding option for shifts
$("#Shift").prop("disabled", false);
});
},
error: function (ex) {
alert('Failed to retrieve shifts.' + ex);
}
});
return false;
}
else {
$("#Shift").empty();
$("#Shift").prop("disabled", true);
}
})
});

Required Attribute not firing

The following is my class. I am trying to make a small login form. I have a class LoginApp which has username and password. Both I have made required.
[Required(ErrorMessage="This Is a required field")]
[Display(Name="User Name")]
public string userName { get; set; }
[Required]
[Display(Name = "PassWord")]
public string passWord { get; set; }
Following is my controller where i have used tryUpdateModel for checking.
public ActionResult Login(Models.LoginApp LA)
{
LoginApp LAPP = new LoginApp();
bool g = TryUpdateModel(LAPP);
if (ModelState.IsValid)
{
if (LA.userName == "admin" && LA.passWord == "admin")
return RedirectToAction("LoginSuccessful", new { userName = LA.userName});
else
return RedirectToAction("Index");
}
else
return RedirectToAction("Index");
}
Here is the view.
<div class="container">
#using (Html.BeginForm("Login", "Login"))
{
#Html.ValidationSummary(true)
<div class="row">
<div class="form-group ">
#Html.Label("User Name", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(Model => Model.userName, "", new { #class = "form-control" })
#Html.ValidationMessageFor(Model => Model.userName)
</div>
</div>
<br />
<br />
<div class="form-group ">
#Html.Label("PassWord", new { #class = "col-md-2 control-label" })
<div class="col-md-10 ">
#Html.PasswordFor(u => u.passWord, new { #class = "form-control" })
#Html.ValidationMessageFor(Model => Model.passWord)
</div>
</div>
<br />
<br />
<div class="form-group ">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Log in" class="btn btn-default" />
<input type="button" id="btn" value="Reset" onclick="" class="btn btn-default" />
</div>
</div>
</div>
}
</div>
When I click the log in button without supplying the username or password it doesn't give me validation messages. Where I am going wrong.
You didn't include the validate.js and unobtrusiveon the page.
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
You should check if the ModelState.IsValid in the controller in order to ake the validation in back-end too (so in both side)

How to Localize Custom Module Content in Orchard CMS?

I had made some modules in my Orchard site using MVC 3 and EFW .I had also made contents using Orchard Cms like I made some static pages using CMS . But my module has dynamic data which user can add and change them using site admin area.But my question is that I had to localize my app but how ? I made enable Culture picker module and added po files of my desire language and added translations of every content of my site but when I change culture only my CMS content changes.my custom module which I made using MVC 3 and EntityFrameWork does not have any offect of site Culture how to localize my custom module contents ?
public class ContactUsController : Controller
{
DbEntities context = new DbEntities();
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult SaveContacts(FormCollection frmData) {
try
{
using (new TransactionScope(TransactionScopeOption.Suppress))
{
if (ModelState.IsValid == true)
{
Imidus_ContactUs ob = new Imidus_ContactUs();
ob.UserName = frmData["UserName"];
ob.Subject = frmData["Subject"];
ob.Message = frmData["Message"];
ob.Email = frmData["Email"];
context.Imidus_ContactUs.Add(ob);
context.SaveChanges();
return RedirectToAction("Success", "ContactUs");
}
}
}
catch (Exception ex) {
throw ex;
}
return View("Index");
}
public ActionResult Success()
{
return View();
}
}
<fieldset class="contact-form">
#using (Html.BeginForm("SaveContacts", "ContactUs", FormMethod.Post, new { id = "frmContact" }))
{
#Html.ValidationSummary(true)
<span class="errormsg"></span>
<label for="cname">
Name</label>
<div class="editor-field">
<input id="cname" name="UserName" minlength="2" type="text" required />
</div>
<div class="editor-label">
<label for="cemail">
E-Mail</label>
</div>
<div class="editor-field">
<input id="cemail" type="email" name="Email" required />
#* #Html.EditorFor(model => model.Email, new { Class = "input-xlarge" })
*#
</div>
<div class="editor-label">
<label for="csubject">
Subject</label>
</div>
<div class="editor-field">
<input id="csubject" name="Subject" minlength="2" type="text" required />
#* #Html.EditorFor(model => model.Subject, new { Class = "input-xlarge" })
#Html.ValidationMessageFor(model => model.Subject)*#
</div>
<div class="editor-label">
<label for="cMessage">
Message</label>
</div>
<div class="editor-field">
<input id="cMessage" name="Message" minlength="15" type="text" required />
#* #Html.TextAreaFor(model => model.Message)
#Html.ValidationMessageFor(model => model.Message)*#
</div>
<p>
<input type="submit" value="Submit" class="btn btn-primary block my-btn" />
</p>
}
</fieldset>

Resources