Как получить данные из формы, используя method="post"? Как запросить данные в моем контроллере?
Я пытаюсь получить данные из моего HTML-кода, такого как "acquringCode", "cardAcceptor" и "merchantId". Я не могу понять, как получить эти данные в моем контроллере. Я знаю его request.form. Я считаю, что я делаю это неправильно. Есть ли более простой способ передать объект или каждое имя в качестве параметра через функцию?
Html
<script type="text/javascript">
$(document).ready(function () {
$("#SavetreventLocationLookupAddButton").click(function () {
$("#addSaveTreventLocationLookup").submit();
});
});
Добавить поиск местоположения Trevent
<form id="addSaveTreventLocationLookup" method="post" action="<%: Url.Action("AddSaveTreventLocationLookup","Prod") %>">
<table>
<tr>
<td colspan="3" class="tableHeader">Trevent Location Lookup Detail</td>
</tr>
<tr>
<td colspan="2" class="label">Acquiring Institution Identification Code:</td>
<td class="content">
<input type="text" maxlength="200" name="AcquiringInstitutionIdentificationCode" id="AcquiringInstitutionIdentificationCode" />
</td>
</tr>
<tr>
<td colspan="2" class="label">Card Acceptor Identification Code:</td>
<td class="content">
<input type="text" maxlength="200" name="CardAcceptorIdentificationCode" id="CardAcceptorIdentificationCode" />
</td>
</tr>
<tr>
<td colspan="2" class="label">Merchant Id:</td>
<td class="content">
<input type="text" maxlength="200" name="MerchantId" id="MerchantId" />
</td>
</tr>
<tr>
<td colspan="3" class="tableFooter">
<br />
<a id ="SavetreventLocationLookupAddButton" href="#" class="regularButton">Add</a>
<a href="javascript:history.back()" class="regularButton">Cancel</a>
</td>
</tr>
</table>
</form>
регулятора,
[HttpPost]
[AuthorizeAttribute(AdminRoles = "AddTreventLocationLookup")]
public ActionResult AddSaveTreventLocationLookup()
{
try
{
string acquiringInstitutionIdentificationCode; //= Request.Form["AcquiringInstitutionIdentificationCode"] ?? string.Empty;
string cardAcceptorIdentificationCode;// =/Request["CardAcceptorIdentificationCode"] ?? string.Empty;
string merchantId;// = Request["MerchantID"] ?? string.Empty;
if (!string.IsNullOrEmpty(Request.Form["AcquiringInstitutionIdentificationCode"]))
{
acquiringInstitutionIdentificationCode = Request.Form["AcquiringInstitutionIdentificationCode"];
}
if (!string.IsNullOrEmpty(Request.Form["CardAcceptorIdentificationCode"]))
{
cardAcceptorIdentificationCode = Request.Form["CardAcceptorIdentificationCode"];
}
if (!string.IsNullOrEmpty(Request.Form["MerchantID"]))
{
merchantId = Request.Form["MerchantID"];
}
AdminProductionServices.TreventLocationLookup treventLocationLookup = Administrator.Models.AdminProduction.TreventLocationLookup.loadTreventLocationLookup(Guid.Empty, Guid.Empty, string.Empty, string.Empty, string.Empty)[0];
treventLocationLookup.acquiringInstitutionIdentifcationCode = acquiringInstitutionIdentificationCode;
treventLocationLookup.cardAcceptorIdentificationCode = cardAcceptorIdentificationCode;
treventLocationLookup.merchantId = merchantId;
Administrator.Models.AdminProduction.TreventLocationLookup.addTreventLocationLookup(treventLocationLookup);
}
catch(Exception e)
{
Commons.ErrorHandling.ReportError("Administrator.Controller.ProdController AddSaveTreventLocationLookup()", e);
}
return RedirectToAction("SearchTreventLocationLookup", "Prod");
}
4 ответа
Создайте модель представления, подобную этой:
public class TreventLocationLookupViewModel
{
public string InstitutionIdentificationCode {get; set;}
public string CardAcceptorIdentificationCode {get; set;}
public string MerchantId {get; set;}
}
а затем использовать его в своем действии так:
public ActionResult AddSaveTreventLocationLookup(TreventLocationLookupViewModel model)
{
AdminProductionServices.TreventLocationLookup treventLocationLookup = Administrator.Models.AdminProduction.TreventLocationLookup.loadTreventLocationLookup(Guid.Empty, Guid.Empty, string.Empty, string.Empty, string.Empty)[0];
treventLocationLookup.acquiringInstitutionIdentifcationCode = model.InstitutionIdentificationCode;
treventLocationLookup.cardAcceptorIdentificationCode = model.CardAcceptorIdentificationCode;
treventLocationLookup.merchantId = model.MerchantId;
Administrator.Models.AdminProduction.TreventLocationLookup.addTreventLocationLookup(treventLocationLookup);
return RedirectToAction("SearchTreventLocationLookup", "Prod");
}
MVC позаботится о привязке значений запроса к модели для вас. В любом случае, чтобы получить представление, вы должны прочитать о связующих моделях и валидации.
Ответ Веблока полностью правильный. Но вы также можете привязать к простым переменным в вашем действии.
public ActionResult AddSaveTreventLocationLookup(string InstitutionIdentificationCode, string CardAcceptorIdentificationCode, string MerchantId)
{
..code..
}
Пока ваши поля формы называются так же, как переменные, MVC будет связывать их для вас после поиска возможных источников в request.form, request.querystring и переменных маршрутизации.
// Также обратите внимание, что, поскольку у меня есть движок бритвы, вы заметите, что мои представления используют // @html.TextBoxFor... Однако, если у вас нет движка бритвы... тогда вы будете использовать // Что-то вроде <% Html.TextBoxFor, //
// логика контроллера
[HttpPost]
public ActionResult AddSaveTreventLocationLookup(TreventModel model)
{
string acquiringInstitutionIdentificationCode;
string cardAcceptorIdentificationCode;
string merchantId;
acquiringInstitutionIdentificationCode = model.AcquiringInstitutionIdentificationCode;
cardAcceptorIdentificationCode = model.CardAcceptorIdentificationCode;
merchantId = model.MerchantId;
//
return RedirectToAction("TreventLookUp");
}
public ActionResult TreventLookUp()
{
return View("TreventLookUp");
}
}
// Просмотр логики
@model MvcApplication2.Models.TreventModel
<form id="addSaveTreventLocationLookup" method="post"action="@Url.Action("AddSaveTreventLocationLookup", "Test")">
<table>
<tr>
<td colspan="3" class="tableHeader">Trevent Location Lookup Detail</td>
</tr>
<tr>
<td colspan="2" class="label">Acquiring Institution Identification Code:</td>
<td class="content">
@*<input type="text" maxlength="200" name="AcquiringInstitutionIdentificationCode" id="AcquiringInstitutionIdentificationCode" />*@
@Html.TextBoxFor(m=>m.AcquiringInstitutionIdentificationCode , new {maxlength="200"})
</td>
</tr>
<tr>
<td colspan="2" class="label">Card Acceptor Identification Code:</td>
<td class="content">
@*<input type="text" maxlength="200" name="CardAcceptorIdentificationCode" id="CardAcceptorIdentificationCode" />*@
@Html.TextBoxFor(m => m.CardAcceptorIdentificationCode, new { maxlength = "200" })
</td>
</tr>
<tr>
<td colspan="2" class="label">Merchant Id:</td>
<td class="content">
@* <input type="text" maxlength="200" name="MerchantId" id="MerchantId" />*@
@Html.TextBoxFor(m => m.MerchantId, new { maxlength = "200" })
</td>
</tr>
<tr>
<td colspan="3" class="tableFooter">
<br />
<a id ="SavetreventLocationLookupAddButton" href="#" class="regularButton">Add</a>
<a href="javascript:history.back()" class="regularButton">Cancel</a>
</td>
</tr>
</table>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#SavetreventLocationLookupAddButton").click(function () {
$("#addSaveTreventLocationLookup").submit();
});
});
</script>
//View Model
public class TreventModel
{
public string AcquiringInstitutionIdentificationCode { get; set; }
public string CardAcceptorIdentificationCode { get; set; }
public string MerchantId { get; set; }
}
Попробуйте, добавив параметр FormCollection в действие AddSaveTreventLocationLookup.
Как это:
public ActionResult AddSaveTreventLocationLookup(FormCollection formCollection)
{
// now you can get the values you want
string acquiringInstitutionIdentificationCode = formCollection["AcquiringInstitutionIdentificationCode"];
.......