كيفية دعم نماذج متعددة تستهدف نفس إجراء الإنشاء في نفس الصفحة؟
-
29-09-2020 - |
سؤال
أريد الحصول على نموذجين منفصلين في صفحة إنشاء واحدة وإجراء واحد في وحدة التحكم لكل نموذج.
في العرض:
<% using (Html.BeginForm()) { %>
// Contents of the first (EditorFor(Model.Product) form.
<input type="submit" />
<% } %>
<% using (Html.BeginForm()) { %>
// Contents of the second (generic input) form.
<input type="submit" />
<% } %>
في وحدة التحكم:
// Empty for GET request
public ActionResult Create() {
return View(new ProductViewModel("", new Product()));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(Product product) {
return View(new ProductViewModel("", product));
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(string genericInput) {
if (/* problems with the generic input */) {
ModelState.AddModelError("genericInput", "you donkey");
}
if (ModelState.IsValid) {
// Create a product from the generic input and add to database
return RedirectToAction("Details", "Products", new { id = product.ID });
}
return View(new ProductViewModel(genericInput, new Product()));
}
النتائج في "The current request for action 'MyMethod' on controller type 'MyController' is ambiguous between the following action methods"
- خطأ أو يتم استدعاء إجراء الإنشاء الخاطئ.
حلول؟
- الجمع بين هذين المنشورين إنشاء إجراءات في جمهور واحد
ActionResult Create(Product product, string genericInput);
- قم بتسمية أحد إجراءات POST Create بشكل مختلف وأضف الاسم الجديد إلى الاسم المقابل
Html.BeginForm()
ليس لدي أي فكرة عما هي المحاذير في هذه.كيف يمكنك حل هذا؟
المحلول
في الواقع، أعتقد أنه يمكنك القيام بذلك إذا كنت أكثر تحديدًا في استدعاء BeginForm() الخاص بك.
Using(Html.BeginForm<ControllerName>(c => c.Create((Product)null)) { }
Using(Html.BeginForm<ControllerName>(c => c.Create((string)null)) { }
نصائح أخرى
لا يمكن أن يكون لديك إجراءين بنفس الاسم والفعل ويختلفان فقط في أنواع الوسائط.قد تكون تسمية الإجراءين بشكل مختلف من قبل IMHO فكرة جيدة على افتراض أنهما يؤديان مهام مختلفة ويأخذان مدخلات مختلفة.
لا تنتمي إلى StackOverflow